Suppose I have a file a.txt in which every line contains the line number (starting from 1) followed by a space and then followed by a name (the name of an item in a folder like e.g - something.mkv). I want to sort the items in that folder according to given order (i.e. given line numbers), the order given in file a.txt. How to do that ?
2 Answers
Is there any other method to rename the files in the directory (all at once) by prefixing them with order number and an underscore (order is defined in a.txt file).
cat order.txt | sed -r 's/ *([0-9]+)[ \t]+(.*)/mv \2 \1_\2/'
This line pipes the content line wise into sed which separates the order number and the file name to create the rename command.
The command expects (at least) one space or tab character between line number and file name. If you have different separators in the file add them between [
and ]
.
The result of that script can either be piped into a bash script by appending
> renameWithOrdernumber.sh
or executed directly, then append
| bash
Example of an a.txt:
1 d
2 a
3 c
4 b
Then we can transform it with
$ awk '{printf "mv %s %s\n", $2, $1"_"$2}' a.txt
mv d 1_d
mv a 2_a
mv c 3_c
mv b 4_b
and if we like the result, execute it in bash
$ awk '{printf "mv %s %s\n", $2, $1"_"$2}' a.txt | bash
ls
) has options to change the files order for display.