Without using a for
loop? You can use the perl rename
utility (also known as prename
, or file-rename
or perl-rename
on some distros) to create the subdirectories and rename the files into them. For example:
$ rename -v 'BEGIN{mkdir "book"};
if (m/chapter(\d+)/) {
my $d="book/chapter$1";
mkdir $d;
$_ = "$d/$_"
}' *
chapter1.txt renamed as book/chapter1/chapter1.txt
chapter2.txt renamed as book/chapter2/chapter2.txt
chapter3.txt renamed as book/chapter3/chapter3.txt
chapter4.txt renamed as book/chapter4/chapter4.txt
chapter5.txt renamed as book/chapter5/chapter5.txt
English summary of the script:
If the current filename ($_
) matches the regex chapter(\d+)
then extract the chapter number from the filename (i.e. $1
, which is the first and only capture group in the regex, the (\d+)
), create a directory for the chapter, and then rename the current file into the directory.
Non-matching filenames are ignored.
perl rename
only attempts to rename a file if the rename script changes the value of $_
. It also refuses to overwrite an existing file unless you force it to with the -f
option.
perl rename allows you to use any perl code within the rename script (but note that it the use strict
pragma is in force so you need to declare your variables). If the code changes $_
, the file will be renamed. If not, it won't.
Note that it's good practice to do a dry-run first with the -n
option to make sure that rename is going to do what you want it to (recovering from a bad bulk rename can be a major PITA). -n
doesn't rename any files, it just shows what it would do. Replace the -n
with -v
(as I have above) to get verbose output, or just remove the -n
for silent operation.
for
loops? This is the perfect application for one. – Panki Jul 01 '21 at 13:47for x in $(seq 1 10); do echo $x; done
and work your way up :) – Panki Jul 01 '21 at 13:52mv
target with a wildcard can create problems? Imagine you have directoriesbook/chapter1
andbook/chapter11
- your shell would expand your command tomv chapter1<whatever files> book/chapter1 book/chapter11
and allchapter1
files plus the entire folderbook/chapter1
would end up inbook/chapter11
. – AdminBee Jul 01 '21 at 14:10