У меня есть текстовый файл с 3 столбцами, разделенными знаком : как отсортировать второй столбец по последним 2 цифрам столбца 2?

Вам нужно для установки графического окружения на сервер. Замените dnf на yum, если dnf не работает.

# dnf install @kde-desktop              [KDE Desktop]
# dnf install @xfce-desktop             [XFCE Desktop]
# dnf install @mate-desktop             [Mate Desktop]
0
05.06.2019, 14:00
2 ответа

Предполагая, что второе:-поле с разделителями всегда содержит пять цифр:

$ sort -t ':' -k2.4,2n file
195.92.211.48:21023:400
195.92.211.47:21029:400

-k2.4,2nуказывает sortиспользовать второе поле, начиная с символа 4 (это то, что делает .4)до конца поля в качестве ключа сортировки, и сортировать ввод в числовом виде на этой клавише (nв конце ). Для численной сортировки по целому второму полю вы бы использовали -k2,2n. Мы используем -t ':', чтобы сказать, что поля разделены двоеточием.

Вы можете увидеть, что для сортировки используются правильные числа, если вы запустите команду с --debug(, показывающую как GNU sort, так и sortв OpenBSD здесь):

$ gsort --debug -t ':' -k2.4,2n file
gsort: text ordering performed using simple byte comparison
195.92.211.48:21023:400
                 __
_______________________
195.92.211.47:21029:400
                 __
_______________________
$ sort --debug -t ':' -k2.4,2n file
Memory to be used for sorting: 2139060224
sort_method=heapsort
; k1=<23>, k2=<29>; s1=<195.92.211.48:21023:400>, s2=<195.92.211.47:21029:400>; cmp1=-1
195.92.211.48:21023:400
195.92.211.47:21029:400
3
28.01.2020, 02:15

Используйтеsort -t: -nk2.4

-t uses the delimiter :
-n for numerical sort
-k your key is the second column

Ключевые определения очень хорошо объяснены в info sort.

‘-k POS1[,POS2]’

‘--key=POS1[,POS2]’

Specify a sort field that consists of the part of the line between POS1 and POS2 (or the end of the line, if POS2 is omitted), inclusive.

Each POS has the form ‘F[.C][OPTS]’, where F is the number of the field to use, and C is the number of the first character from the beginning of the field. Fields and character positions are numbered starting with 1; a character position of zero in POS2 indicates the field’s last character. If ‘.C’ is omitted from POS1, it defaults to 1 (the beginning of the field); if omitted from POS2, it defaults to 0 (the end of the field). OPTS are ordering options, allowing individual keys to be sorted according to different rules; see below for details. Keys can span multiple fields.

Example: To sort on the second field, use ‘--key=2,2’ (‘-k 2,2’). See below for more notes on keys and more examples. See also the ‘--debug’ option to help determine the part of the line being used in the sort.

2
28.01.2020, 02:15

Теги

Похожие вопросы