Live Chat!

Rename multiple files

* * * * ½ 7 votos

November 5th, 2006 toydi Posted in Common, Regular Expression, for, mv | Hits: 74906 |

Often over time, we will want to reorganize a group of files by renaming them.

To rename *.txt to *.bak
(e.g. to rename ham.txt to ham.bak)

for f in *.txt; do mv "$f" "${f%.txt}.bak"; done

To remove ‘new-’ from new-*
(e.g. to rename new-ham.txt to ham.txt)

for f in new-*; do mv "$f" "${f#new-}"; done

${variable%pattern} vs ${variable#pattern}

The funny-looking symbol, ${f%.txt} is a useful match-and-remove string operator:

If the pattern ‘.txt’ matches the end of variable $f, it will remove the matching part (that’s ‘.txt‘) and return the rest. Try this:

f=new-ham.txt      # define $f as 'new-ham.txt'
echo ${f%.txt}     # display 'new-ham'

What about ${f#new-}? It’s almost the same, but it matches the pattern at the beginning of the variable.

echo ${f#new-}     # display 'ham.txt'

14 Responses to “Rename multiple files”

  1. Great tips, this is an example related to regular expression, why don’t add in to RE category?

  2. As you wish. ;-)

  3. This is the 2-cent tip that worths $1,000,00 dollars. Thank you very much. It’s what I was looking for days ago.

  4. rename ’s/\.txt/.bak/’ *.txt

  5. Cool, that is convenient. I have trace it . It is a perl script ‘prename’ in my box.

  6. Hi
    You can accomplish the same trick and much more using Vladimir Lanin’s mmv utility. It is available for most distros.

  7. At first I was like “NO WAY” that can be done, “it looks exactly like bash/sh syntx” but then I realized that it was on linux.

    MS DOS have some syntax in common with UNIX shell syntaxes, but not that much.

    BTW I saw that you could use a hosts.deny in MS Windows (just put it in C:\hosts.deny apparently). I dont think it has anything to do with the linux/BSD tcp wrappers though ;D

  8. great tip! i can now speed up my `split`s w00t

  9. I tried rename ’s/\.txt/.bak/’ *.txt but it does nothing what so ever on my system (Suse 10.2). Looks simple enough but nothing ever is with Linux, lol

  10. Ubuntu 7.04 works

  11. thanks for the tip

  12. /usr/bin/rename appears to come-with Perl (v5.8.8 on my system). It’s a Perl script.

  13. this is very useful. first time i thik it can’t be possible. but the question was logical.so i tryed to find it.

  14. [...] reveal about you?DavidGorcey.com- A funny blog by David Gorcey to keep you marginally entertainedRename multiple files ? Linux by Examples Tags baby shower favor wedding favor party favor candy favor bar wrappers wrapper This product [...]

Leave a Reply