Rename multiple files in Linux

(Below tips are copied from LINUX BY EXAMPLE.com)

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'
Advertisement

7 Responses to “Rename multiple files in Linux”

  1. Hameed Khan Says:

    Nice tip, especially for those, who don’t have knowledge of bash programming.

    Thanks for sharing it.

  2. Marc Grabanski Says:

    Thank you! this just came in handy for me.

  3. Emilio Enriquez Says:

    Thanks for your sharing this. It was exactly what I was looking for.

  4. Hristo Hristov Says:

    Thanks quick and concise exactly what I needed!

  5. laptop Says:

    laptop…

    [...]Rename multiple files in Linux « My Notebook[...]…

  6. notebooks Says:

    notebooks…

    [...]Rename multiple files in Linux « My Notebook[...]…

  7. jak kupić Says:

    jak kupić…

    [...]Rename multiple files in Linux « My Notebook[...]…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.