Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a bunch of files like this:

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


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
up vote 5 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"

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... – SpaceDog 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 – SpaceDog Apr 7 '12 at 0:36
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

Your Answer


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.