Issue
I have a text file containing below lines.
Number: "472"
displayname: "jack holi"
Number: "392"
displayname: "david"
Number: "376"
displayname: "joly"
Number: "481"
displayname: "john doe"
....
How to sort them in ascending order by number and have output like below
Number: "376"
displayname: "joly"
Number: "392"
displayname: "david"
Number: "472"
displayname: "jack holi"
Number: "481"
displayname: "john doe"
Solution
Perl to the rescue!
perl -e 'BEGIN { $/ = "" }
print for map $_->[1],
sort { $a->[0] <=> $b->[0] }
map [ /Number: "(\d+)"/, $_ ],
<>;' -- input.txt
The BEGIN block turns on paragraph mode, i.e. file is read by the diamond operator in paragraphs, i.e. blocks of texts separated by empty lines.
It uses Schwartzian Transform, i.e. it maps each block to a pair Number, block
, then sorts the pairs by the numbers and maps them back to the blocks, now in correct order.
Answered By - choroba Answer Checked By - Marie Seifert (WPSolving Admin)