Shell Scripting – How to Copy Multiple Files and Keep Their Extensions

file-copyrenamescriptingshellwildcards

I am looping through a number of files, and $file represents the current file.

How can I make copies or renames and keep the extension the same for this current file?

e.g. if $file = x.jpg

How to make a copy of $file's with a filename of x_orig.jpg

So far I have:

for file in /tmp/p/DSC*.JPG; do
  cp $file $file+'_orig'.JPG
done

but that copies the file

DSCF1748.JPG

to

DSCF1748.JPG+_orig.JPG

whereas I want a copy named

DSCF1748_orig.JPG

Similarly, using cp $file "$file"_orig.JPG

results in files such as DSCF1748.JPG_orig.JPG

I want to get the _orig in the middle of the filename…

Best Answer

You can use bash's string substitution features for that:

for file in /tmp/p/DSC*.JPG; do
  cp "$file" "${file%.JPG}"_orig.JPG
done

The general format is ${string%substring} which will remove substring from the end of string. For example:

$ f=foobar.JPG; echo "${f%.JPG}"
foobar
Related Question