Reputation: 713
php, command line, windows.
I need to sequentially number each .txt file in a directory. Any way I can specify the first number to use in the sequence in the command line when I type the script? (Instead of every time manually editing the script itself).
Or instead (even better) being prompted to enter the first number twice (for confirmation)?
Like, in command line ("285603" is just an example number):
c:\a\b\currentworkingdir>php c:\scripts\number.php 285603
or (even better)
c:\a\b\currentworkingdir>php c:\scripts\number.php
c:\a\b\currentworkingdir>Enter first number:
c:\a\b\currentworkingdir>Re-enter first number:
The numbering script:
<?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);
?>
Any hints please?
Upvotes: 1
Views: 35
Reputation: 881
You should use $argv
variable. It is an array with a first element indicating script file name and next elements are arguments passed.
Given you type php script.php 1234
in the console, $argv
variable is as follows:
array(4) {
[0]=>
string(10) "script.php"
[1]=>
string(4) "1234"
}
EDIT: Your code should be like below:
<?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);
?>
Upvotes: 1
Reputation: 17436
Command-line arguments are available to PHP in the global $argv
array, as described in the manual here
This array contains the name of the script, followed by each proceeding argument. In your case, when you run:
php c:\scripts\number.php 285603
The argument 285603 will be available as the variable $argv[1]
. You can replace your $i
variable with this, and the script will work as intended.
Upvotes: 1