Shell – Copy/rename multiple files using regular expression (shell script)

file managementrenamesedshell-script

I have a collection of files matching a pattern such as 'assignment02.cc', 'assignment02.h', 'assignment02.txt', etc. I would like to copy/rename these files into 'assignment03.cc', 'assignment03.h', 'assignment03.txt', and so on.

I suspect this should be straight forward using a shell script and sed. So far I have:

OLD_NO=$1
NEW_NO=$2

echo "Moving from $OLD_NO to $NEW_NO"

for name in assignment$OLD_NO.* ; do
  newname=$(echo $name | sed 's/\(.*\)$OLD_NO\(.*\)/\1xx$NEW_NO\2/')
  echo "$name -> $newname"
  # mv -v $name $newname
done

Unfortunately the way I am invoking sed always returns the input string $name and doesn't actually do the regex find/replace.

Note: Looking on the internet there is a rename command which has this functionality, but that isn't available on my MacBook.

Best Answer

Using sed here introduces more complexity than it's worth. Use the shell's built-in text manipulation features. For example, ${name#assignment02} strips the prefix assignment02 from $name.

for name in assignment02.*; do
  mv "$name" "assignment03${name#assignment02}"
done

The double quotes are not necessary if you are sure the file names contain no shell special characters.

If you have zsh available, its zmv function is helpful for these kinds of renamings.

autoload zmv
zmv '(assignment)02.(*)' '${1}03.$2'
Related Question