George
George

Reputation: 7317

Renaming all files in a folder with a prefix and in ascending order

How does one rename

random_files.jpg
that\ may\ contain\ spaces.jpg
and_differ_in_extensions.mp4

to

PREFIX_1.jpg
PREFIX_2.jpg
PREFIX_3.mp4

via bash script? More formally, how do I rename all files in a directory into an ordered list of form PREFIX_N.ext where .ext is preserved from the original filename.

My attempt below

for f in *; do 
    [[ -f "$f" ]] && mv "$f" "PREFIX_$f"
done 

changes only prefixes.

Upvotes: 1

Views: 200

Answers (2)

123
123

Reputation: 11216

You can loop over the files using *, and then access them with a quoted var to preserve all the special characters.

You can then use parameter expansion to remove the start of the file up to ., and append that to your new filename.

x=1;for i in *;do [[ -f "$i" ]] && mv "$i" "PREFIX_$((x++)).${i##*.}";done

If you know x isn't already set though you can remove the assignment at the start and change $((x++)) to $((++x))

Upvotes: 1

anubhava
anubhava

Reputation: 785156

You can use this in a for loop using find:

while IFS= read -rd '' file; do
   ext="${file##*.}"
   echo mv "$file" "PREFIX_$((++i)).$ext"
done < <(find . -type f -name '*.*' -maxdepth 1 -print0)

Once satisfied with the output, remove echo before mv command.

Upvotes: 1

Related Questions