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.
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 ofls
, 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 themv
command is fairly obvious.The following script will do the job:
This I just test it and it's worked for me.