Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 know there are lots of such questions, but I couldn't find one (or a combination of several), which describes the things I want to do. I think I need to use regular expressions, but I am not very good with that. I use zsh. I have a folder with files, which I want to rename:

  • I want the files challenge1.rb, challenge2.rb, challenge3.rb, etc. to be renamed to c1.rb, c2.rb etc. Similarly task1.rb and similar must be renamed to t1.rb etc.

  • sample_spec_c1.rb, sample_spec_c2.rb etc. must be renamed to c1_spec.rb, c2_spec.rb etc.

So I guess I need some combination of regular expressions and iteration, but I don't know how to write the bash script.

share|improve this question
up vote 2 down vote accepted

Here is a short script which will do what you want. You can call the script with a list of files like: ./scriptname *.rb or with directories (it will recurse them): ./scriptname .

Do not forget to set the executable bit: chmod a+x scriptname.


suff=rb     # suffix of files to rename

script="$0" # this script name for recursion

for f in "$@" ; do
    if test -d "$f" ; then
        echo "=== recursing directory $f"
        find "$f" -type f -name "*.$suff" -exec "$script" {} +
    elif test -f "$f" ; then
        d="$(dirname "$f")"
        b="$(basename "$f")"
        r="$(echo "$b" | sed -r "s/^([a-zA-Z])[a-zA-Z]*([0-9]+\.${suff})\$/\1\2/;s/^[a-zA-Z]+_([a-zA-Z]+)_([a-zA-Z]+[0-9]+)(\.${suff})\$/\2_\1\3/")"
        echo "-- renaming $f -> $d/$r"
        mv "$f" "$d/$r"
share|improve this answer
I am sorry, there was a typo: mv "$f" "$d/$f". It was renaming to the same name. Now it is corrected. I also made the regex more precise (string beginning and end specified). – pabouk Nov 5 '13 at 10:58

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.