0

This command in a bash prompt properly sorts files in a target folder. The sort occurs on the third field in descending order as shown below:

$ find -printf '%f\n' | sort -r -k3
bfilename  Desc 1068%.html
afilename  Desc  298%.html

I want to show the filenames in sorted order as links in a browser. My idea is to create and prepend a unique four-digit index number to the respective filename as shown below:

0001 filename  Desc 1068%.html
0002 filename  Desc  298%.html

This question uses output from sort to rename files in a loop but I don't understand how to modify the code for my task:

https://unix.stackexchange.com/questions/564672/rename-files-based-on-their-ranked-number

Can I pipe the output of the sort command to another process that either renames the files by prepending an index or that creates a new folder with sorted links to the original files? I would like to experiment with both options. I would like to use bash but a python script is also an option.

EDIT

$ n=1; find -printf '%f\n' | sort -r -k3 | while read f; do printf "%04d" $n; echo " $f"; let n+=1; done
0001 Desc 1068%.html
0002 Desc  298%.html

0018 Desc 17%.html 0019 .

The command above works to print to standard out but includes an unwanted extra dot item 0019. Tree gives 18 files in the directory.

$ find -printf '%f\n' | sort -r -k3 | nl -n rz
000001 Desc 1068%.html
000002 Desc  298%.html

000018 Desc 17%.html 000019 .

Based on comment the output is shown. I'd like to drop out the first two leading zeroes and not generate the final line with a dot. The output goes to standard out. I still don't know how to make this rename the files in the current directory and/or generate soft links in a new directory?

1 Answers1

1

The reason that you're getting the . entry is because you're not narrowing the find down to -type f.

The format for nl is unfortunately not tweakable, but with the awk in the comments you can set the number of digits by adjusting the %05d to e.g. %03d ...

find -maxdepth 1  -type f -printf "%f\n"| sort -r -k3 | awk '{printf "ln -s \x22%s\x22 \x22PATH/TO/LINK/DIRECOTRY/%03d%s\x22\n",$0,NR,$0 }'|bash

If you were to rename rather than symlink replacing the ln -s inside the awk statement with mv and dropping the path component ...

tink
  • 2,059