Hello,
On 2019-04-28 11:23 a.m., Peng Yu wrote:
In the 2nd example, it is not sorted as what I want. Why is it so?
$ printf '%s\t%s\n' a 1 a 2 |grep --color=always a | sort -k 2,2nr
a 2
a 1
$ printf '%s\t%s\n' a 1 a 2 | grep --color=always a$'\t' | sort -k 2,2nr
a 1
a 2
The 'grep' in the second example highlights *both* the 'a' character
and the 'tab' character.
This means that the ANSI sequence to restore color (\033 [ m \033 [ K)
appears *after* the tab, and is then parsed by 'sort' as the beginning
of the second field:
$ printf '%s\t%s\n' a 1 a 2 | grep --color=always a$'\t' | od -tc -An
033 [ 0 1 ; 3 1 m 033 [ K a \t 033 [ m
033 [ K 1 \n 033 [ 0 1 ; 3 1 m 033 [ K
a \t 033 [ m 033 [ K 2 \n
And annotated:
First line, first field:
033 [ 0 1 ; 3 1 m 033 [ K a
\t
First line, second field:
033 [ m 033 [ K 1
\n
Second line, first field:
033 [ 0 1 ; 3 1 m 033 [ K a
\t
Second line, second field:
033 [ m 033 [ K 2
\n
Using "--debug" will give a hint as to what went wrong:
$ printf '%s\t%s\n' a 1 a 2 | grep --color=always a$'\t' \
| sort -k2,2nr --debug
sort: using ‘en_CA.utf8’ sorting rules
a>1
^ no match for key
________________
a>2
^ no match for key
________________
The "no match for key" message means that the 2nd field failed to be
parsed as a numeric value.
regards,
-assaf