sub199 sub199 - 14 days ago 7
Linux Question

Add string in filename before pattern

I need to add string in between of filename where a pattern is matched.

Sample filenames:

file_1_my001
file_11_my0012
file_65_my_012


I would like to rename them as:

file_1_my_copied_001
file_11_my_copied_0012
file_65_my_copied_012


Pattern is
<any string>0<any string>


My logic was to first fetch the numerical format starting with 0, store in variable as pattern, then search for the variable and replace it by
_copied_<variable>
. I tried fetching numbers as:

ls | sed -e s/[^0-9]//g


but above command is fetching all numbers in filename eg.
1001, 110012, 65012
I am unable to make it search for numerical format starting with 0. Please guide.

Answer

with perl based rename command:

$ touch file_1_my001 file_11_my0012 file_65_my_012
$ rename -n 's/_?(?=0)/_copied_/' file_*
rename(file_11_my0012, file_11_my_copied_0012)
rename(file_1_my001, file_1_my_copied_001)
rename(file_65_my_012, file_65_my_copied_012)
  • _?(?=0) zero or one instance of _ followed by 0
  • -n option is for dry run, after it looks good, remove the option for actual renaming


If perl based rename is not available, try:

$ for file in file_* ; do echo mv "$file" $(echo "$file" | sed 's/_\?0/_copied_0/'); done
mv file_11_my0012 file_11_my_copied_0012
mv file_1_my001 file_1_my_copied_001
mv file_65_my_012 file_65_my_copied_012

If it is okay, change echo mv to mv for actual renaming


If optional _ before 0 is not present, it is easier to use parameter expansion

$ touch file_1_my001 file_11_my0012 file_65_my012
$ for file in file_* ; do echo mv "$file" "${file/0/_copied_0}"; done
mv file_11_my0012 file_11_my_copied_0012
mv file_1_my001 file_1_my_copied_001
mv file_65_my012 file_65_my_copied_012
Comments