echo "ab\na a" | sort -c sort: -:...">

"sort -c -k1" also compares the second field?

"sort" correctly reports that these two lines are out of order:

> echo "ab\na a" | sort -c sort: -:2: disorder: aa 

How can I sort the sort only for the first field of each row? I tried:

 > echo "ab\na a" | sort -c -k1 sort: -:2: disorder: aa 

but this failed as indicated above.

Is it possible to sort the comparison of the first field of each row, or should I use something like sed to trim the lines before comparing them?

EDIT: I am using "sort (GNU coreutils) 7.2". I tried using a different field separator, but this did not help:

 > echo "ab\na a" | sort -k1 -c -t" " sort: -:2: disorder: aa 

although I'm sure the default space is the default delimiter.

+4
source share
1 answer

The following works as expected:

 echo "ab\na a" | sort -s -c -k1,1 

There were two problems in your sort call:

  • The -k argument is a key definition that defines the start and end positions. If the end position is omitted, the last line field is used by default, not the start field. -k1,1 specifies both values, telling sort not to include the second field in the comparison.

  • sort is unstable by default, which means that it does not guarantee a violation of the order of strings that are compared equal. Documentation citation:

Finally, in the extreme case, when all keys are compared equal, sort compares the entire string, as if it werenโ€™t for the order parameters, except --reverse ( -r ) were specified. The --stable ( -s ) -s disables this โ€œlast resort comparisonโ€ so that the lines in which all fields are equal are left in their original relative order.

+5
source

Source: https://habr.com/ru/post/1490161/


All Articles