Reputation: 59
I have some files:
$ ls
00000.ABC
00001.ABC
00002.ABC
00003.ABC
00004.ABC
00005.ABC
I want to change these to start at a certain number, for example 00055.ABC
so the new files look like:
$ ls
00055.ABC
00056.ABC
00057.ABC
00058.ABC
00059.ABC
00060.ABC
I understand about for loops to loop through each file, for example for file in ls { }
but I'm not sure about the incrementing number starting at a certain number so appreciate any help.
Upvotes: 2
Views: 2933
Reputation: 12203
This should work:
for f in *.ABC; do
num=$(basename "$f" .ABC)
num2=$(printf "%05d" $((num + 55)))
echo mv "$f" "$num2.ABC"
done
Notes:
I am assuming your files all follow the pattern of digits followed by .ABC
, so that basename $f .ABC
extracts the number. You'll have to adjust the num=
line if this assumption does not hold.
$(( ... ))
is the bash
syntax to do arithmetic operations.
(printf "%05d" ...)
is here to pad zeroes in front of the number, otherwise you'd just get 55
etc.
Remove the echo
once you're convinced it's doing the right thing.
EDIT Warning: the new set of filenames should not overlap the old set of filenames, or you might lose some files. Carefully choosing the order the mv
commands are run could solve the issue, but putting the files in a new directory as they are renamed and moving them back after would be much simpler.
EDIT:
@MarkSetchell pointed out in the comments that you want sequential numbering that is not based on the original file names, in which case this loop would work instead:
i=55 # choose your starting destination file number here
for f in *.ABC; do
dest=$(printf "%05d" $i).ABC
echo mv "$f" "$dest"
i=$((i + 1))
done
Upvotes: 1
Reputation: 207375
You can do this easily with rename
, which is actually just a Perl script, and which can be installed on macOS with homebrew using:
brew install rename
The command would then be:
rename --dry-run -XN "00055" -e '$_ = $N' *ABC
Sample Output
'00001.ABC' would be renamed to '00055.ABC'
'00002.ABC' would be renamed to '00056.ABC'
'00003.ABC' would be renamed to '00057.ABC'
'00004.ABC' would be renamed to '00058.ABC'
'00005.ABC' would be renamed to '00059.ABC'
If that looks correct, you would remove the --dry-run
and do it again. Using rename
has the benefit that it will not clobber (overwrite) files and it will tell you what it is going to do, without actually changing anything, if you use the --dry-run
option. It is also immensely powerful - it can do lowercase, camelcase, uppercase, remove control characters, call any Perl module and calculate any expression or substitution you can think of.
Upvotes: 2