Add suffix to all files without specific extension and retain the file extension

filenamesrenamexargs

I have a directory that has .zip files and other files (all files have an extension), and I want to add a suffix to all files without the .zip extension. I am able to pick off a suffix and place it into a variable $suffix, and so I tried the following code:

ls -I "*.zip"| xargs -I {} mv {} {}_"$suffix"

This lists all files without .zip and is close (but wrong). It incorrectly yields the following results on file.csv:

file.csv_suffix

I want file_suffix.csv — how can I edit my code to retain the extension on the file?

Best Answer

find + bash approaches:

export suffix="test"

a) with find -exec action:

find your_folder -type f ! -name "*.zip" -exec bash -c 'f=$1; if [[ "$f" =~ .*\.[^.]*$ ]]; then ext=".${f##*\.}"; else ext=""; fi; mv "$f" "${f%.*}_$suffix$ext"' x {} \;


b) Or with bash while loop:

find your_folder/ -type f ! -name "*.zip" -print0 | while read -d $'\0' f; do 
    if [[ "$f" =~ .*\.[^.]*$ ]]; then
        ext=".${f##*\.}"
    else 
        ext=""
    fi
    mv "$f" "${f%.*}_$suffix$ext"
done
Related Question