通过提示输入 php 中的第一个数字来对文件进行顺序编号

Sequentially number files by being prompted for the first number in php

php,命令行,windows.

我需要对目录中的每个 .txt 文件按顺序编号。当我键入脚本时,我可以通过任何方式在命令行中的序列中指定要使用的 第一个数字 吗? (而不是每次都手动编辑脚本本身)。

或者(甚至更好)被提示输入第一个数字两次(用于确认)?

例如,在命令行中(“285603”只是一个示例数字):

c:\a\b\currentworkingdir>php c:\scripts\number.php 285603

或(更好)

c:\a\b\currentworkingdir>php c:\scripts\number.php
c:\a\b\currentworkingdir>Enter first number: 
c:\a\b\currentworkingdir>Re-enter first number: 

编号脚本:

<?php
$dir = opendir('.');
// i want to enter this number OR being prompted for it to enter twice in the command line 
$i = 285603;
while (false !== ($file = readdir($dir)))
{
    if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'txt')
    { 
        $newName = $i . '.txt';
        rename($file, $newName);
        $i++;
    }
}
closedir($dir);
?>

有什么提示吗?

命令行参数可用于全局 $argv 数组中的 PHP,as described in the manual here

此数组包含脚本名称,后跟每个后续参数。在你的情况下,当你 运行:

php c:\scripts\number.php 285603

参数 285603 将作为变量 $argv[1] 可用。您可以用这个替换 $i 变量,脚本将按预期工作。

您应该使用 $argv 变量。它是一个数组,第一个元素指示脚本文件名,下一个元素是传递的参数。 如果您在控制台中键入 php script.php 1234$argv 变量如下:

array(4) {
  [0]=>
  string(10) "script.php"
  [1]=>
  string(4) "1234"
}

编辑:您的代码应如下所示:

<?php
# CONFIRMATION
echo 'Are you sure you want to do this [y/N]';
$confirmation = trim(fgets( STDIN));
if ($confirmation !== 'y') {
   exit (0);
}

$dir = opendir('.');
$i = $argv[1];
while (false !== ($file = readdir($dir)))
{
    if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'txt')
    { 
        $newName = $i . '.txt';
        rename($file, $newName);
        $i++;
    }
}
closedir($dir);
?>