-2

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 ?

3
  • You can't. The order of the files is determined by the file system. Usually it is die Order in which they are added. But the question is: why do you want that? Almost any file viewer (and even ls) has options to change the files order for display. Feb 10, 2017 at 17:37
  • 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). This way when the file manager keeps the files in the directory in sorted form, the actual order is maintained (as in a.txt file) and the file names are only prefixed by the order number and an underscore. Feb 10, 2017 at 20:29
  • This comment and an example should be included in the question.
    – user216043
    Sep 20, 2017 at 7:39

2 Answers 2

0

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

0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .