2

I have a directory of files. There is a line in each file that says:

# order: N

where N is an integer number. I want to list all files in the directory (or even include them in wrapper script) according to that N number. Is this possible from a bash command-line?

4

With GNU grep, and assuming file names don't contain colon or newline characters:

$ ls
bar     baz     foo     freeble quux
$ cat ./*
# order: 3
# order: 2
# order: 1
# order: 4
# order: 5
$ grep -m1 -EH '^# order: [0-9]+$' ./* | sort -n -k3 | cut -d: -f1
foo
baz
bar
freeble
quux
| improve this answer | |
  • Better use grep -H, otherwise it won't work if there is only one file. – xenoid Nov 29 '17 at 16:41
  • Good catch. Done. – DopeGhoti Nov 29 '17 at 16:42
2

With single GNU awk process:

awk 'BEGIN{ PROCINFO["sorted_in"]="@val_num_asc" }
     /order: [0-9]+/{ a[FILENAME]=$NF; nextfile }
     END{ for(i in a) print i }' ./*
| improve this answer | |
2

With zsh, you can define a glob sorting order based on the content of those lines with:

byOrder() REPLY=$(grep '^# order:' < $REPLY)

and then use it for example with:

printf '%s\n' *(.no+byOrder)

or

sorted_file_list=(*(.no+byOrder))

(also adding a . to the glob qualifier to only consider regular files (not directories, fifos, symlinks...)).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.