Rename files numerically (date/time order) [duplicate]
I have 200 files in a folder. I downloaded them in a certain order -- often only a few seconds apart. I would like to append a number to the beginning of each of the files.
So the first file I downloaded (the oldest one) would need to change from name.txt
to 001_name.txt
.
All the way up to the last file (most recently downloaded) changing from name.txt
to 200_name.txt
.
How can I do it using the command-line?
The following will break on files containing newlines, but should work the rest of the time. It will sort the files based on the time they were last modified, rather than their actual creation time, because Ubuntu doesn't store the creation time of files. So if you've modified the files since you downloaded them, you won't get an accurate ordering.
n=0; ls -tr | while read i; do n=$((n+1)); mv -- "$i" "$(printf '%03d' "$n")"_"$i"; done
ls -tr
sorts files by modification time, oldest first (and when you pipe the output of ls it automatically lists files one-per-line rather than the standard way of doing things -- it should be noted that this is a GNU-ism, if you have to work on another *nix with a different version of ls
, this might not be the case). while read i
takes that list and goes over each item one at a time, and the rest of it does the actual renaming.
n=$((n+1))
increments the variable $n
by one. There could be problems if this had been set beforehand, so to be on the safe side you should set it to 0 at the beginning of the line.
$(printf '%03d' "$n")
prints the number contained in the variable $n, padded to three zeros (so 001, 002 ... 087 ... 999). I hope that the mv
command is fairly obvious.
The following script will do the job:
#!/bin/bash
if [ $# -ne 1 ];then
echo "Usage: `basename $0` DIRECTORY"
exit 1
fi
count=1
ls -tr $@ | while read file; do
if [ $count -lt 10 ]; then
mv -v $file '00'$count'_'$file
elif [ $count -lt 100 ]; then
mv -v $file '0'$count'_'$file
else
mv -v $file '0'$count'_'$file
fi
count=$(($count+1))
done
This I just test it and it's worked for me.