0

I'm not sure if I'm asking the right way or if it is possible at all. I want to change the name of some files using their own name.

Let's assume I have file1, file2, and file3. I want to do something like:

mv file* file{recover_number}_xyz

To get: file1_xyz, file2_xyz and file3_xyz

fixer1234
  • 27,486
AFP_555
  • 145

1 Answers1

1

There are tools which can apply a regex search-and-replace to the entire filename, e.g. perl-rename (also commonly called prename). In such tools, you would match multiple digits with \d+ or [0-9]+ inside a "capture group" (parentheses), and reference it later with $1 or \1 depending on program.

For example:

prename -v 's/file(\d+)$/file$1_xyz/' file[123]

prename -v 's/(file\d+)$/$1_xyz/' file[123]

(The -v option makes prename print out the changes. You can use -n to print changes without actually renaming anything.)

You can also achieve this using just mv and sed:

for old in file[123]; do
    new=$(sed -r 's/file([0-9]+)$/file\1_xyz/' <<< "$old")
    mv -v "$old" "$new"
done

But if you look closely, you don't actually need the number. All you're doing is appending some static text anyway, like this:

prename 's/$/_xyz/' file[123]

for f in file[123]; do
    mv "$f" "${f}_xyz"
done
u1686_grawity
  • 452,512