Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question
    
THe is posted on your previous questio. This is double posting. –  val0x00ff 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

2 Answers 2

up vote 3 down vote accepted

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
share|improve this answer
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
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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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