3

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.

Duck
  • 4,674

1 Answers1

6

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.

  • almost there, but files with space are not being processed... – Duck Apr 07 '12 at 00:24
  • @Digital Robot -- try it with double quotes (edited) – William Pursell Apr 07 '12 at 00:30
  • ahhhhhhhhhhhhhhh, thanks!!!!!! that's now working perfectly. You are awesome! :D – Duck Apr 07 '12 at 00: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 07 '12 at 05:14
  • There's never a need for quotes around $(). The operator itself serves as a quoting mechanism. – William Pursell Apr 07 '12 at 13:47