Thursday, May 2, 2024
17
rated 0 times [  17] [ 0]  / answers: 1 / hits: 7398  / 2 Years ago, thu, february 10, 2022, 2:56:51

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?


More From » command-line

 Answers
3

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.


[#29280] Friday, February 11, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
afisird

Total Points: 193
Total Questions: 112
Total Answers: 111

Location: Angola
Member since Mon, Jul 12, 2021
3 Years ago
afisird questions
Wed, Jul 27, 22, 03:53, 2 Years ago
Sun, Mar 12, 23, 18:05, 1 Year ago
Sun, Dec 11, 22, 01:19, 1 Year ago
;