rename all files in folder to numbered list 1.jpg

2019-03-09 05:27发布

问题:

I have a folder full of images with several different random file names to help organize this mess I would like to, in one command rename all of them to a sequential order so if I have 100 files it starts off naming the first file file-1.jpg file-2.jpg etc. Is this possible in one command?

回答1:

The most concise command line to do this I can think of is

ls | cat -n | while read n f; do mv "$f" "file-$n.jpg"; done

ls lists the files in the current directory and cat -n adds line numbers. The while loop reads the resulting numbered list of files line by line, stores the line number in the variable n and the filename in the variable f and performs the rename.



回答2:

I was able to solve my problem by writing a bash script

#!/bin/sh
num=1
for file in *.jpg; do
       mv "$file" "$(printf "%u" $num).jpg"
       let num=$num+1
done