Renaming files in a folder to sequential numbers

2019-01-03 11:50发布

I want to rename the files in a directory to sequential numbers. Based on creation date of the files.

For Example sadf.jpg to 0001.jpg, wrjr3.jpg to 0002.jpg and so on, the number of leading zeroes depending on the total amount of files (no need for extra zeroes if not needed).

24条回答
【Aperson】
2楼-- · 2019-01-03 12:06

Here a another solution with "rename" command:

find -name 'access.log.*.gz' | sort -Vr | rename 's/(\d+)/$1+1/ge'
查看更多
相关推荐>>
3楼-- · 2019-01-03 12:06

Pero's answer got me here :)

I wanted to rename files relative to time as the image viewers did not display images in time order.

ls -tr *.jpg | # list jpegs relative to time
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command
查看更多
【Aperson】
4楼-- · 2019-01-03 12:07
a=1

for i in *.jpg; do
 mv -- "$i" "$a.jpg"
 a=`expr $a + 1`
done
查看更多
聊天终结者
5楼-- · 2019-01-03 12:07

This oneliner lists all files in the current directory, sorts by creation timestamp in reverse order (means the oldest file is at the beginning) and renames automatically with trailing zeros as required by the amount of files. The file extension will be preserved.

I usually have only one folder since years for mobile phone pictures and movies. Applying this command, my pictures and movies are ready then for a slideshow in the correct order on the tv or archiving as well.

Be aware that if you have file name collisions, you are losing files. So first rename to something odd like temp001.jpg and then execute to your final file name.

DIGITS=$(ls | wc -l | xargs | wc -c | xargs); ls -tcr | cat -n | while read n f; do mv "$f" "$(printf "%0${DIGITS}d" $n).${f##*.}"; done
查看更多
【Aperson】
6楼-- · 2019-01-03 12:08

Beauty in one line

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

change extension with desired PNG, Jpg or some-other.

查看更多
等我变得足够好
7楼-- · 2019-01-03 12:12

A very simple bash one liner that keeps the original extensions, adds leading zeros, and also works in OSX:

num=0; for i in *; do mv "$i" "$(printf '%04d' $num).${i#*.}"; ((num++)); done

Simplified version of http://ubuntuforums.org/showthread.php?t=1355021

查看更多
登录 后发表回答