Home > Uncategorized > Rename multiple files in Linux

Rename multiple files in Linux


Rename multiple files in Linux

By linansg

(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'
Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: