3

How do you ignore or is there a way to change the sort order of empty keys when using sort -k?

# cat afile
a  b
11 20
93 45
55
26
09 31

How can I sort the empty column b values at the bottom so it looks like this:

a  b
11 20
09 31
93 45
26
55

Here's what I get instead:

sort -k 2b tmp/file
26
55
11 20
09 31
93 45

2 Answers 2

4

You can add a special sort key for empty fields and remove it again after sorting. That key must not be present in your input data and has to be greater than every (numeric) value.

For example:

$ awk '$2 ~ /^$/ { print $1, "XXX"; next; } {print $0 }' f \
    | sort -k2b
    | sed 's/XXX$//'
11 20
09 31
93 45
26 
55
3

Another approach:

awk '{print NF, $0}' | sort -k1,1rn -k3 | cut -d' ' -f2-

That is add another column with the number of fields and sort first by reverse number of fields.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .