sorting - How to sort with linux command, while treat 3 lines as 1 block and sort based on the first line of each block -


how sort linux command, while treat 3 lines 1 block , sort based on first line of each block?

i know can concat 3 lines 1 line , sort. file big, , don't wan't generate temp file sorting.

sort sorts lines of text files, record separated newlines. exception, supports \0 record separator, there no way change logic of how records separated.

you can make use of above exception implement decorate-sort-undecorate pattern, this:

chunk | sort -z -t' ' -k1 | unchunk 

chunk combines every 3 lines line1\0line2\0line3\n, allow sort -z three-lined chunk single record, , -t'\n' -k1 sort first field in record. unchunk changes \0 \n.

expressed in perl, chunk this:

perl -pe 'chomp;$_.=($.%3)?"\n":"\0"' 

(a similar incantation written in awk or sed, , c version not longer.)

unchunk no more tr '\0' '\n'. complete sort is:

perl -pe 'chomp;$_.=($.%3)?"\n":"\0"' | sort -z -t' ' -k1 | tr '\0' '\n' 

given input file of

b 2nd b line bla 3rd b line line other line x first x line other x line 

...the above pipeline produces:

a line other line b 2nd b line bla 3rd b line x first x line other x line 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -