8

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.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175

4 Answers4

5

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'
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
3

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

phemmer
  • 70,657
  • 19
  • 188
  • 223
0

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'

user unknown
  • 10,267
  • 3
  • 35
  • 58
-1

One way you could do it is:

ls -1  | sed "s/\(.*\)\..*$/mv '&' '\1.txt'/" | sh
mazianni
  • 679
  • 4
  • 3
  • 2
    [Do not parse the output of `ls`](http://mywiki.wooledge.org/ParsingLs). 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