Using sed
, I can search and replace text in a file. Is there a way I can do search and replace of filenames? For example if I have a bunch of files in a folder with names like these:
- foo01
- foo02
- bar001
- bar002
I would like to quickly rename all of the ones starting with foo so that they have 3 digits instead of 2.
Answer
#!/bin/bash
shopt -s nullglob
for file in foo*
do
filename=${file%%[0-9]*}
num=${file##*[^0-9]}
newnum=$(printf "%03d" $num)
newfile=${filename}${newnum}
mv "$file" "$newfile"
done
No comments:
Post a Comment