I want to rename multiple jpg files in a directory so they have 9 digit sequence number. I also want the files to be sorted by date from oldest to newest. I came up with this:
ls -tr | nl -v 100000000 | while read n f; do mv "$f" "$n.jpg"; done
this renames the files as I want them but the sequence numbers do not follow the date. I have also tried doing
ls -tr | cat -n .....
but that does not allow me to sepecify the starting sequence number. Any suggestions what's wrong with my syntax? Any other ways of achieving my goal? Thanks
DIR="/tmp/images"
FILELIST=$(ls -tr ${DIR})
n=1
for file in ${FILELIST}; do
printf -v digit "%09d" $n
mv "$DIR/${file}" "$DIR/${digit}.jpg"
n=$[n + 1]
done
Something like this? Then you can use n to sepecify the starting sequence number. However, if you have spaces in your file names this would not work.
If any of your filename contains a whitespace, you can use the following:
i=100000000
find -type f -printf '%T@ %p\0' | \
sort -zk1nr | \
sed -z 's/^[^ ]* //' | \
xargs -0 -I % echo % | \
while read f; do
mv "$f" "$(printf "%09d" $i).jpg"
let i++
done
Note that this doesn't use ls
for parsing, but uses the null byte as field separator in the different commands, respectively set as \\0
, -z
, -0
.
The find
command prints the file time together with the name. Then the file are sort
ed and sed
removes the timestamp. xargs
is giving the filenames to the mv
command through read
.
If using external tool is acceptable, you can use rnm :
rnm -ns '/i/.jpg' -si 100000000 -s/mt *.jpg
-ns
: Name string (new name).
/i/
: Index (A name string rule).
-si
: Option that sets starting index.
-s/mt
: Sort according to modification time.
If you want an arbitrary increment value:
rnm -ns '/i/.jpg' -si 100000000 -inc 45 -s/mt *.jpg
-inc
: Specify an increment value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.