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 bunch of files like this:

pic100.png
pig102.png
box103a.png
superb103b.png
px103c.png
rotor110 - new.png
ready1323 (yellow car).png
motorhome1036x red circle.png
...

so, you can notice that files may have 3 parts:

  • a prefix that can be any string
  • a number that may contain a suffix like "a", "b", etc.
  • an optional ending, that is always a string and starts with a space, like " (yellow car)", " red circle", etc.

What I need is this: I want in one operation to:

  • change the prefix to the one I want
  • keep the number and the suffix (a, b, c...) if there's one
  • get rid of the ending

using the first example, I may want to transform that in

object100.png
object102.png
object103a.png
object103b.png
object103c.png
object110.png
object1323.png
object1036x.png

how do I do that? As you see the only thing I am keeping is the number and the suffix "a, b, c" when there is one...

To make it simple, the command must operate in all files in a given directory.

Thanks in advance.

share|improve this question
add comment

1 Answer

up vote 4 down vote accepted

A standard way to do this sort of thing is to use sed to generate the new file name:

ls | while read file; do
     new=$( echo $file | sed 's/[^0-9]*\([^ ]*\)[^.]*\(\..*\)*/object\1\2/' )
     mv "$file" "$new"
done

Before you do that, you should examine the commands to ensure they do what you wnat, and make a backup.

share|improve this answer
    
almost there, but files with space are not being processed... –  Digital Robot Apr 7 '12 at 0:24
    
@Digital Robot -- try it with double quotes (edited) –  William Pursell Apr 7 '12 at 0:30
    
ahhhhhhhhhhhhhhh, thanks!!!!!! that's now working perfectly. You are awesome! :D –  Digital Robot Apr 7 '12 at 0:36
1  
If you are going to consider even a single space in filenames, then it is most likely worthwhile to consider multiple spaces... new="$( echo "$file" | sed 's/[^0-9]*\([^ ]*\)[^.]*\(\..*\)*/object\1\2/' )" .... The basic issue is that $var can easily cause problems with embedded whitespace. Using double-quotes solves this problem: echo "$var" or var="a    b" or var="$(cat file)" –  Peter.O Apr 7 '12 at 5:14
    
There's never a need for quotes around $(). The operator itself serves as a quoting mechanism. –  William Pursell Apr 7 '12 at 13:47
add comment

Your Answer

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.