Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

This one has baffled me – I'm actually trying to make a Thunar custom action to copy the selected file into the same directory appending a number before the extension, e.g.

cp file.ext file_1.ext

Some commands seem to do this automatically like the mogrify -format (except obviously the extension changes).

For example I'd like to copy an image file so that I can mogrify -resize the copy (which will be overwritten).

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

The common way to do this in bash is with parameter expansion. If the file variable holds the filename do something like this:

name=${file%.*}
extension=${file##*.}
i=1
new_file="${name}_${i}.${extension}

cp "$file" "$new_file"

To use this in a script (duplicate.sh say), do something like this:

#!/bin/bash

name=${1%.*}
extension=${1##*.}
infix="${2:-_1}"

cp -v "$1" "${name}${infix}.${extension}"

Then call it as:

duplicate.sh FILE INFIX
share|improve this answer
    
You could of course wrap that in a shell function and actually copy the file. –  slhck Jul 12 '12 at 21:43
    
Forgot it was about copying, modified answer. –  Thor Jul 12 '12 at 21:45
2  
cp "$name"{,_1}."${extension} can be used to eliminate the need for the new_file variable. –  chepner Jul 12 '12 at 21:50
    
@chepner Post that as an answer. –  slhck Jul 12 '12 at 22:02
1  
for safety, one could include a loop checking whether new_file already exists, to avoid it being overwritten (something like while [ -f "$new_file" ]; do i=i+1; new_file="${name}_${i}.${extension}; done). –  Izzy Jul 13 '12 at 9:25
show 16 more comments

This is just a slightly shorter version of @Thor's answer:

name=${file%.*}
extension=${file##*.}

cp "$name"{,_1}."$extension"
share|improve this answer
add comment

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.