Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort ignoring the blank line

Tags:

unix

sorting

I have a data looks like this

<some blah! blah!>|201451|<some blah! blah!>

<some blah! blah!>|201441|<some blah! blah!>

<some blah! blah!>|201431|<some blah! blah!>

<some blah! blah!>|201421|<some blah! blah!>

I have to sort it to

<some blah! blah!>|201421|<some blah! blah!>

<some blah! blah!>|201431|<some blah! blah!>

<some blah! blah!>|201441|<some blah! blah!>

<some blah! blah!>|201451|<some blah! blah!>

I have tried using both these:

sort -t"|" -k4.5,4.6 -b data
LC_ALL=c sort -t"|" -k4.5,4.6 -b data

but it always gives me

<FOUR BLANK SPACE>
<some blah! blah!>|201421|<some blah! blah!>
<some blah! blah!>|201431|<some blah! blah!>
<some blah! blah!>|201441|<some blah! blah!>
<some blah! blah!>|201451|<some blah! blah!>

I want to maintain the space with the sorted value. How do I do so??

Basically I have to ignore the line space and not remove them...

like image 896
Kaze..Sujan Avatar asked Jul 04 '14 15:07

Kaze..Sujan


2 Answers

Here is a solution with sorting removing blank lines first and then inserting the blank lines back using sed:

grep -v '^$' <file> |  sort -t'|' -k 4.5,4.6 | sed 's/$/\n/'
like image 118
heemayl Avatar answered Sep 28 '22 22:09

heemayl


Try to execute:

sort -t"|" -k4.5,4.6 data | grep -v "^$" | awk '{print $0"\n"}'
like image 41
kgkoutio Avatar answered Sep 28 '22 20:09

kgkoutio