Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
    
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
add comment

4 Answers

One way you could do it is:

ls -1  | sed "s/\(.*\)\..*$/mv '&' '\1.txt'/" | sh
share|improve this answer
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 Feb 11 '11 at 19:28
add comment

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'
share|improve this answer
add comment

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*)

share|improve this answer
    
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 Feb 11 '11 at 19:23
    
Ah, didnt know you were on osx, bummer –  Patrick Feb 11 '11 at 20:27
add comment

A different approach:

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

In the long run: Try to get 'rename'

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.