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:


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

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.

  • Change the single quotes to double quotes. If you have single quotes around the sed command, then $OLD_NO and $NEW_NO won't get expanded. – Mikel Feb 9 '11 at 21:02
  • newname=$(echo $name | tr $OLD_NO $NEW_NO) – Nizam Mohamed Feb 7 '15 at 12:43

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}"

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'

Youre already thinking too complex

rename 02 03 *02*

'rename' replaces the first arg ('02') with the second arg ('03') in the name of all files given on arg3 or after (*02*)

  • The rename command with this syntax is a Linux utility, not available on OSX (and not even available by this name on most Debian and Ubuntu installations). – Gilles 'SO- stop being evil' Feb 11 '11 at 19:23
  • Ah, didnt know you were on osx, bummer – phemmer Feb 11 '11 at 20:27
  • Rename is a perl script, so it will probably run on OS X. Found it here using google: tips.webdesign10.com/files/rename.pl.txt – azzid Feb 7 '15 at 12:15

A different approach:

for ext in {cc,h,txt}
  echo mv assignment02.$ext assignment03.$ext

In the long run: Try to get 'rename'


One way you could do it is:

ls -1  | sed "s/\(.*\)\..*$/mv '&' '\1.txt'/" | sh
  • 2
    Do not parse the output of ls. And generating a shell script is a sure way to shoot yourself in the head. Vault Boy's question contains a reasonable approach on the shell side, just missing the right sed incantation and some quoting. – Gilles 'SO- stop being evil' Feb 11 '11 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy