1

i have a directory listing like

seascaperecovered0088crop.jpg 
seascaperecovered0096crop.jpg
seascaperecovered0098crop.jpg
seascaperecovered0101crop.jpg
seascaperecovered0103crop.jpg
seascaperecovered0105crop.jpg
seascaperecovered0107crop.jpg
seascaperecovered0112crop.jpg
seascaperecovered0119crop.jpg
seascaperecovered0122crop.jpg

and i want to rename all files as seen here:

seascape_0122.jpg

i have tried something like this:

for f in `ls | egrep 'seascaperecovered.*\.jpg'`; 
do mv $f ${f/seascaperecovered/seascape}; 
done

i have read that you can do this with mv, rename, sed, awk, etc. can someone point me to the easiest (and clearest, hopefully) way of accomplishing this in UNIX? FWIW, I am ssh'd into a Linux machine and running a bash shell.

thanks, jml

jml
  • 1,745
  • 6
  • 29
  • 55
  • i would also be interested in why my example wouldn't work. i get a number of errors like: "mv: cannot stat `\033[33mseascaperecovered0088crop.jpg\033[0m': No such file or directory" – jml Aug 16 '11 at 23:57

2 Answers2

5

Very straightforward:

for i in seascaperecovered*.jpg; do A=${i/crop/}; mv $i ${A/recovered/_}; done

(Put echo before the mv first for a dry run.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • nice! what about removing the "crop" bit? should i pipe again? – jml Aug 16 '11 at 23:59
  • Sneaky, I almost noticed that too late :-) – Kerrek SB Aug 17 '11 at 00:00
  • No prob. I do this sort of stuff pretty regularly, and I'm always so happy I have a Bash in Windows; I really couldn't imagine life without one! – Kerrek SB Aug 17 '11 at 00:05
  • That is pretty amazing, I didn't know you could do that in Bash. What is this operation called, so I can read more about it? – Chriszuma Oct 27 '11 at 17:24
  • @Chriszuma: Which operation? For for-do-done loop is a Bash built-in construction (`man bash`). The curly braces fall under "parameter substitution" (or something like that). – Kerrek SB Oct 27 '11 at 17:36
  • Sorry, I was talking about the curly braces. That is a very powerful tool I'd never seen before. Thanks! – Chriszuma Oct 27 '11 at 17:55
1

With bash regular expressions

for file in *; do 
  [[ "$file" =~ [0-9]+ ]] && mv "$file" seascape_${BASH_REMATCH[0]}.jpg 
done
glenn jackman
  • 238,783
  • 38
  • 220
  • 352