user1757703
user1757703

Reputation: 3015

Add suffix to all files in the directory with an extension

How to add a suffix to all files in the current directory in bash?

Here is what I've tried, but it keeps adding an extra .png to the filename.

for file in *.png; do mv "$file" "${file}_3.6.14.png"; done

Upvotes: 41

Views: 45892

Answers (4)

0-_-0
0-_-0

Reputation: 1473

If you know how to rename a single file to your liking programmatically

fname=myfile.png
mv $fname ${fname%.png}_extended.png

you can batch apply this command with xargs:

find -name "*.png" | xargs -n1 bash -c 'mv $0 ${0%.png}_extended.png'

Explanation

We pipe the list of files to xargs and tell it to process one line at a time with the -n1 flag. We then tell xargs to call bash on each instance and provide it with the code to execute via the -c flag. The $0 references the first input argument the bash receives. If you need other string substitutions than ${0%.png} there are many cheat sheets such as https://devhints.io/bash.

For more complex substitutions you provide multiple arguments using -n2; these can be collected with $0, $1, etc..

This use of piping + xargs + bash -c is fairly general. In the short example above, beware that I assumed proper file names (without special characters).

Upvotes: 2

0-_-0
0-_-0

Reputation: 1473

If you are familiar with regular expressions sed is quite nice.

a) modify the regular expression to your liking and inspect the output

ls | sed -E "s/(.*)\.png$/\1_foo\.png/

b) add the p flag, so that sed provides you the old and new paths. Feed this to xargs with -n2, meaning that it should keep the pairing of 2 arguments.

ls | sed -E "p;s/(.*)\.png/\1_foo\.png/" | xargs -n2 mv

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174706

You could do this through rename command,

rename 's/\.png/_3.6.14.png/' *.png

Through bash,

for i in *.png; do mv "$i" "${i%.*}_3.6.14.png"; done

It replaces .png in all the .png files with _3.6.14.png.

  • ${i%.*} Anything after last dot would be cutdown. So .png part would be cutoff from the filename.
  • mv $i ${i%.*}_3.6.14.png Rename original .png files with the filename+_3.6.14.png.

Upvotes: 29

Barmar
Barmar

Reputation: 781068

for file in *.png; do
    mv "$file" "${file%.png}_3.6.14.png"
done

${file%.png} expands to ${file} with the .png suffix removed.

Upvotes: 67

Related Questions