Use of regex in bash with mv

Erik Apostol picture Erik Apostol · Dec 19, 2016 · Viewed 7.9k times · Source

I have 4 files to rename:

./01:
I0010001  I0020001

./02:
I0010001  I0020001

I want to add auxiliary filename .dcm to each file, so I have tried:

$ mv \(*/*\) \1.dcm
mv: cannot stat '(*/*)': No such file or directory

$ mv \(./*/*\) \1.dcm
mv: cannot stat '(./*/*)': No such file or directory

$ mv \(./\*/\*\) \1.dcm
mv: cannot stat '(./*/*)': No such file or directory

$ mv "\(./*/*\)" "\1.dcm"
mv: cannot stat '\(./*/*\)': No such file or directory

$ mv 0\([1-2]\)/I00\([1-2\)]0001 0\1/I00\20001.dcm
mv: cannot stat '0([1-2])/I00([1-2)]0001': No such file or directory

$ mv "0\([1-2]\)/I00\([1-2\)]0001" "0\1/I00\20001.dcm"
mv: cannot stat '0\([1-2]\)/I00\([1-2\)]0001': No such file or directory

$ mv "0\([1-2]\)/I00\([1-2]\)0001" "0\1/I00\20001.dcm"
mv: cannot stat '0\([1-2]\)/I00\([1-2]\)0001': No such file or directory

$ mv "0\([[:digit:]]\)/I00\([[:digit:]]\)0001" "0\1/I00\20001.dcm"
mv: cannot stat '0\([[:digit:]]\)/I00\([[:digit:]]\)0001': No such file or directory

$ mv "0\([1-2]\)\/I00\([1-2]\)0001" "0\1/I00\20001.dcm"
mv: cannot stat '0\([1-2]\)\/I00\([1-2]\)0001': No such file or directory

$ mv \(*\) \1.dcm
mv: cannot stat '(*)': No such file or directory

None of them yield the result I want.

Answer

paxdiablo picture paxdiablo · Dec 19, 2016

You don't really need regular expressions here, this is very simple with a for loop:

for f in 0[12]/I00[12]0001 ; do mv "$f" "${f}.dcm" ; done

For more complex situations, you should be looking into the rename program (prename on some systems), which uses powerful Perl regular expressions to handle the renaming. Though unnecessary here, this simple case would use:

pax> rename -n 's/$/.dcm/' 0[12]/I00[12]0001
rename(I01/I0010001, I01/I0010001.dcm)
rename(I01/I0020001, I01/I0020001.dcm)
rename(I02/I0010001, I02/I0010001.dcm)
rename(I02/I0020001, I02/I0020001.dcm)

That -n is debug mode (print what would happen but don't actually rename). Remove it once you're happy it will do what you want.