Linux sort by field

Sorting data based on second column of a file

I have a file of 2 columns and n number of rows. column1 contains names and column2 age . I want to sort the content of this file in ascending order based on the age (in second column). The result should display the name of the youngest person along with name and then second youngest person and so on. Any suggestions for a one liner shell or bash script.

5 Answers 5

You can use the key option of the sort command, which takes a «field number», so if you wanted the second column:

-n , —numeric-sort compare according to string numerical value

$ cat ages.txt Bob 12 Jane 48 Mark 3 Tashi 54 $ sort -k2 -n ages.txt Mark 3 Bob 12 Jane 48 Tashi 54 

also note that using -h instead of -n will sort human readable values like 2G or 3K as well as numbers separated with commas e.g. 1,234.5

Faced issue with «wrong» ordering. Pay attention to man «*** WARNING *** The locale specified by the environment affects sort order. Set LC_ALL=C to get the traditional sort order that uses native byte values.» (for string match case without -n )

This doesn’t consider spaces in the first column neither works if there are more columns after the second, since -k read until the line end. Supposing it is a TSV file a better solution is sort -t$’\t’ -k2 -n FILE

Solution:

more verbosely written as:

sort —key 2 —numeric-sort filename

Example:

$ cat filename A 12 B 48 C 3 $ sort --key 2 --numeric-sort filename C 3 A 12 B 48 

Explanation:

  • -k # — this argument specifies the first column that will be used to sort. (note that column here is defined as a whitespace delimited field; the argument -k5 will sort starting with the fifth field in each line, not the fifth character in each line)
  • -n — this option specifies a «numeric sort» meaning that column should be interpreted as a row of numbers, instead of text.

More:

Other common options include:

  • -r — this option reverses the sorting order. It can also be written as —reverse.
  • -i — This option ignores non-printable characters. It can also be written as —ignore-nonprinting.
  • -b — This option ignores leading blank spaces, which is handy as white spaces are used to determine the number of rows. It can also be written as —ignore-leading-blanks.
  • -f — This option ignores letter case. «A»==»a». It can also be written as —ignore-case.
  • -t [new separator] — This option makes the preprocessing use a operator other than space. It can also be written as —field-separator.
Читайте также:  Linux ограничения файловой системы

There are other options, but these are the most common and helpful ones, that I use often.

Источник

Команда sort в Linux

Сегодня мы поговорим о команде sort. Это утилита для вывода текстовых строк в определенном порядке. Проще говоря, для сортировки. Ее можно использовать для сортировки текста из одного или нескольких файлов или c помощью нее может быть выполнена сортировка вывода linux для какой-либо команды. Это может быть полезно во многих случаях. Например, отсортировать файлы по размеру в выводе команды du или собрать частотность использования команд из истории.

В этой инструкции мы подробно рассмотрим возможности команды sort Linux, ее опции и разберем несколько примеров использования.

Синтаксис

Уже по традиции подобных статей, сначала рассмотрим общий синтаксис команды:

$ sort опции файл

$ команда | sort опции

Опции

Теперь рассмотрим основные опции утилиты sort.

  • -b — не учитывать пробелы
  • -d — использовать для сортировки только буквы и цифры
  • -i — сортировать только по ASCII символах
  • -n — сортировка строк linux по числовому значению
  • -r — сортировать в обратном порядке
  • — проверить был ли отсортирован файл
  • -o — вывести результат в файл
  • -u — игнорировать повторяющиеся строки
  • -m — объединение ранее отсортированных файлов
  • -k — указать поле по которому нужно сортировать строки, если не задано, сортировка выполняется по всей строке.
  • -f — использовать в качестве разделителя полей ваш символ вместо пробела.

Я понимаю, что многое из всего этого может быть непонятно, но на примерах все станет намного яснее.

Примеры использования sort

Наконец-то мы добрались к теме примеры sort Linux. Давайте сначала создадим файл с несколькими строками, на котором и будем проверять возможности утилиты.

computer
mouse
LAPTOP
data
RedHat
laptop
debian
laptop

Также можно воспользоваться вот такой командой:

echo -e «computer\nmouse\nLAPTOP\ndata\nRedHat\nlaptop\ndebian\nlaptop» > test.txt

Опция -e указывает команде, что нужно обрабатывать спецсимволы, а \n, если кто не знает, не что иное как спецсимвол перевода строки в Linux.

1. Сортировка

Теперь давайте выполним сортировку строк linux в нашем файле:

computer
data
debian
laptop
laptop
LAPTOP
mouse
RedHat

Вот несколько принципов, по которым команда sort linux сортирует строки:

  • Строки с цифрами размещаются выше других строк
  • Строки, начинающиеся с букв нижнего регистра размещаются выше
  • Сортировка выполняется в соответствии алфавиту
  • Строки сначала сортируются по алфавиту, а уже вторично по другим правилам.

2. Обратная сортировка

Отсортируем файл в обратном порядке:

RedHat
mouse
LAPTOP
laptop
laptop
debian
data
computer

3. Сортировка по колонке

Отсортируем вывод команды ls по девятой колонке, то есть по имени файла или папки. Колонку укажем опцией -k:

drwxr-xr-x 6 user user 4096 дек 6 14:29 Android
drwx—— 3 user user 4096 янв 14 22:18 Desktop
drwxr-xr-x 12 user user 4096 янв 14 21:49 Documents
drwx—— 5 user user 12288 янв 15 14:59 Downloads
drwxr-xr-x 7 user user 4096 янв 13 11:42 Lightworks

Сортировка вывода Linux выполняется так же просто как и строк из файла.

4. Сортировка по номеру

Отсортируем вывод команды ls по второй колонке. Для сортировки по числовому значению используется опция -n:

drwx—— 5 user user 12288 янв 15 14:59 Downloads
drwxr-xr-x 6 user user 4096 дек 6 14:29 Android
drwxr-xr-x 7 user user 4096 июн 10 2015 Sources
drwxr-xr-x 7 user user 4096 окт 31 15:08 VirtualBox
drwxr-xr-x 7 user user 4096 янв 13 11:42 Lightworks
drwxr-xr-x 8 user user 12288 янв 11 12:33 Pictures

5. Удаление дубликатов

Команда sort Linux позволяет не только сортировать строки, но и удалять дубликаты. Для этого есть опция -u:

Читайте также:  Installing and uninstalling software in linux

computer
data
debian
laptop
LAPTOP
mouse
RedHat

Теперь строчка laptop не повторяется.

6. Сортировка по нескольким полям

Мы можем сортировать данные по нескольким полям. Например, отсортируем вывод ls по второму первично и вторично девятому полях:

drwxr-xr-x 2 seriyyy95 seriyyy95 4096 дек 6 14:32 Links
drwxr-xr-x 2 seriyyy95 seriyyy95 4096 янв 13 10:43 tmp
drwx—— 3 seriyyy95 seriyyy95 4096 янв 14 22:18 Desktop
drwxr-xr-x 3 seriyyy95 seriyyy95 4096 мар 28 2015 Журналы
drwx—— 4 seriyyy95 seriyyy95 12288 янв 15 15:42 Загрузки

Вот и все. Мы немного приоткрыли занавесу над возможностями сортировки строк linux с помощью команды sort. Если у вас остались вопросы — спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Похожие записи

Оцените статью

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

6 комментариев к “Команда sort в Linux”

У вас в конце списка опций sort указана -f, а описание для неё взято от опции -t. Очепятка, однако 🙂 Ответить

Можно ли отобразить в одном столбце вывод команды full-upgrade? По умолчанию выводится список пакетов для обновления по строчно, что не очень удобно воспринимать. Ответить

Добрый день. Есть файлы:
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
7.txt
8.txt
9.txt
10.txt
11.txt
и так до, например, 1000. Отсортировать нужно по имени.
При использовании получается вот так:
53.ts 978.ts
530.ts 979.ts
531.ts 98.ts
532.ts 980.ts
533.ts 981.ts
534.ts 982.ts
535.ts 983.ts
536.ts 984.ts
537.ts 985.ts
538.ts 986.ts
539.ts 987.ts
54.ts 99.ts
540.ts input_list.txt
541.ts tsMuxeR
542.ts wget.list.m3u8
543.ts wget.log
544.ts Что мешает вам написать книгу.pdf
545.ts то есть 54.ts идет после 539.ts, но так не надо. Как отсортировать имена по порядку? PS ОС — Mac OS. Finder прекрасно сортирует так, как надо, но нужно вывод с путями к файлу положить в текстовый файл. Ответить

Добрый день! Точный ответ на Ваш вопрос даст man sort в Вашей ОС. Основываясь на материале статьи в cygwin провёл опыт:
ls -l | sort -n -k7
команда выше даёт сортировку списка файлов по столбцу даты — всё красиво.
Если поменять -k7 на -k9
, то будут отсортированы в порядке числовой нумерации в начале имён файлов. Ответить

Я как раз столкнулся с такой проблемой — названия директорий были в виде дат.
Решение вот такое :
ls | sort -t «.» -k2,5 -k9
20.10.2020
21.10.2020
22.10.2020
23.10.2020
24.10.2020 Ответить

Источник

How to Sort in Linux Bash by Column

The sort command available in Linux allows users to perform sorting operations on a file or an input. The sort command is handy when we want to get an ordered output of a file ascending, descending, or custom-defined sort order. By default, the sort command does not alter the original file unless the output is redirected back to the file.

This article covers how to use the sort command to perform sorting operations on specific columns in a file.

Basic Usage

The sort command is simple to use and very useful in daily Linux operations. The general syntax of the command is as:

Читайте также:  Canon laserbase mf3228 драйвер linux

The options you pass to the command modifies how the file is sorted and the specific conditions to sort the target file. You can omit the options to use the default sorting parameters.

By default, the sort command:

  • Sorts the alphabets in ascending order.
  • Letters come after numerical values
  • Assigns higher precedence to lowercase letters than to uppercase letters.

For example, to sort a file without options:

Once we run the sort command against the file, we get the information sorted in alphabetical order (ascending).

NOTE: Numerical values take precedence as from the example above.

Sort Command Options

You can use the following options in conjunction with the raw command to modify how the values are sorted.

  • -n – sorts in numerical values.
  • -h – compares human-readable numbers such as 1k, 1G
  • -R – sort in random order but group the identical keys.
  • -r – sort the values in reverse (descending order).
  • -o – save ouput to a file
  • -c – check if the input file is sorted; do not sort if true.
  • -u – show unique values only.
  • -k – sort the data via a specific key (useful when sorting columnar data).

Those are some popular options you can tweak to get the best-sorted result. For more options, check the manual.

How to Sort In Linux Bash By Numerical Values

How to Sort In Linux Bash By Reverse Order

To sort input in reverse order, we use the -r flag. For example:

The command above will sort in ascending alphabetical order (numerical values first) and reverse order.

How to Sort In Linux Bash by Column

Sort allows us to sort a file by columns by using the -k option. Let us start by creating a file with more than one column. In sort, we separate a column by a single space.

In the example file below, we have six columns.

To sort the captains’ file above by their century, we can specify the -k followed by the column number as:

Once we specify the column to sort the data, the sort command will try to sort the values in ascending order. In the example above, the command sorts the values from the earliest century to the latest.

To sort by the first name, set the sort column as 1:

How to Save Sort Output to a File

To save the sorted output to a file, we can use the -o option as:

The command above will sort the captains.txt file by the 5 th column and save the result to the captains_century.txt file.

Conclusion

That is the end of this tutorial on the sort command in Linux. We covered the basics of using the sort command to get the most out of your sorted data. Feel free to explore how you can use the sort command.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Источник

Оцените статью
Adblock
detector