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

but that copies the file




whereas I want a copy named


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...

  • THe is posted on your previous questio. This is double posting. – Valentin Bajrami Sep 29 '13 at 17:44
  • I rolled back your edit because it is generally a good idea to quote variable names, you never know what they might contain. – terdon Sep 29 '13 at 18:23

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

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

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

$ f=foobar.JPG; echo "${f%.JPG}"
  • 1
    You should use "${file%.JPG}" instead. f is not defined, file is. Furthermore (as you mentioned), the /%.abc/ syntax is a bash feature. Dropping the slashes works for this case and makes it POSIX compatible, which makes sense, since conversion scripts often use a POSIX shell. – Marco Sep 29 '13 at 17:47
  • @Marco thanks, answer edited. The f was just a typo left over from the example I was trying. Thanks for letting me know about the POSIX side though, I thought the whole substitution thing was specific to bash. – terdon Sep 29 '13 at 17:50
  • How can I make this match multiple files, and copy then but keeping the extension? – Freedo Nov 7 '17 at 1:28
zcp -o -p '/tmp/p/DSC*.JPG' '$f:r_orig.JPG'

or equivalently

zcp -o -p '/tmp/p/(DSC*).JPG' '/tmp/p/${1}_orig.JPG'

This requires that you run zsh (other shells have nothing like this) and put this in your ~/.zshrc:

autoload -U zmv
alias zcp='zmv -C'
alias zln='zmv -L'

-o -p tells zcp to pass the option -p to the cp command, to preserve the file metadata (especially the modification times).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.