I have to find all files in a directory ending by number (this part is OK) and copy them under a modified name (I don't know how to do this part). Typically:

find $folder -maxdepth 1 -type f -name '*-[0-9]\.jpg'

copy all those files to the same directory, naming them $originalName-mini.jpg


find + bash solution:

find $folder -maxdepth 1 -type f -name "*-[0-9].jpg" -exec \
bash -c 'cp "$1" "${1:0:-4}-mini.jpg"' _ {} \;

You don't really need find here since you're just looking in a single directory, just a shell loop will do the job. You also do not need to escape the dot in a filename globbing pattern.

for pathname in "$folder"/*-[0-9].jpg; do
    [ -f "$pathname" ] && cp "$pathname" "${pathname%-[0-9].jpg}-mini.jpg"

The parameter substitution ${variable%pattern} removes pattern from the end of the value of variable.

The -f test makes absolutely sure that we're dealing with a regular file (or a symbolic link to one) and not a misnamed directory.

Using find to do the same:

find "$folder" -maxdepth 1 -type f -name '*-[0-9].jpg' -exec sh -c '
    for pathname do
        cp "$pathname" "${pathname%-[0-9].jpg}-mini.jpg"
    done' sh {} +

One way to do this is to append following command to your script. Assume that you have the original name in $originalName, you ca use

cp $originalName $(basename $originalName .jpg)-mini.jpg
  • 1
    Can you please include the full script/command into your answer, it's a bit hard to understand how cp should be combined with find here. – nohillside Jun 15 '18 at 9:41

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.