6

I realized I had named a bunch of files in an off-by-one fashion so I wanted to rename any file starting with "1" to the same thing except starting with 2.

For example mv 1.4.5.txt 2.4.5.txt or mv 1-chart.jpg 2-chart.jpg etc.

I tried mv 1* 2* but this was not accepted because it interprets 2* as a directory.

AJJ
  • 862
  • Reopen vote: I feel this is missing a generic approach like rename 's/^[0-9]*/$&+1/e' file would be. – dessert Oct 13 '17 at 08:10
  • 1
    @dessert: The accepted answer to the linked question addresses something very similar though. I'm voting to keep this one closed. – David Foerster Oct 13 '17 at 10:10

2 Answers2

9

Wildcards won't do it. Look at the result of echo mv 1* 2*. A better way is (man rename):

rename 's/^1/2/' 1*
waltinator
  • 36,399
  • 1
    To do it dynamically, use rename 's/^[0-9]*/$&+1/e' file instead, this will increase the number at the beginning of the filename by one. Unfortunately the question got closed so that I can't add another answer for that. – dessert Oct 13 '17 at 06:47
  • @dessert What about "rename any file starting with "1" to the same thing except starting with 2." says "increment the number at the beginning"? – waltinator Oct 13 '17 at 12:52
2

You can use wildcards in that way if you install mmv (although they must be quoted - so that they are interpreted by mmv itself rather than the shell), and the replacement wildcard takes the form #n to re-substitute the nth wildcard from the pattern:

Usage: mmv [-m|x|r|c|o|a|l] [-h] [-d|p] [-g|t] [-v|n] [from to]

Use #[l|u]N in the ``to'' pattern to get the [lowercase|uppercase of the]
string matched by the N'th ``from'' pattern wildcard.

A ``from'' pattern containing wildcards should be quoted when given
on the command line. Also you may need to quote ``to'' pattern.

Use -- as the end of options.

So for example

$ mmv -n -- '1*' 2#1
1.sh -> 2.sh : delete old 2.sh? n
1-chart.jpg -> 2-chart.jpg
1.4.5.txt -> 2.4.5.txt
1.csv -> 2.csv

(The -n option allows you to do a dry-run - remove it to actually rename the files.)

steeldriver
  • 136,215
  • 21
  • 243
  • 336