Sort based on the third column
I’m facing a huge 4-columns file. I’d like to display the sorted file in stdout based on its 3rd column:
Is that enough to perform the trick?
6 Answers 6
would display the file sorted by the 3 rd column assuming the columns are separated by sequences of blanks (ASCII SPC and TAB characters in the POSIX/C locale), according to the sort order defined by the current locale.
Note that the leading blanks are included in the column (the default separator is the transition from a non-blank to a blank), that can make a difference in locales where spaces are not ignored for the purpose of comparison, use the -b option to ignore the leading blanks.
Note that it’s completely independent from the shell (all the shells would parse that command line the same, shells generally don’t have the sort command built in).
-k 3 is to sort on the portion of the lines starting with the 3 rd column (including the leading blanks). In the C locale, because the space and tab characters ranks before all the printable characters, that will generally give you the same result as -k 3,3 (except for lines that have an identical third field),
-u is to retain only one of the lines if there are several that sort identically (that is where the sort key sorts the same (that’s not necessarily the same as being equal)).
cat is the command to concatenate. You don’t need it here.
If the columns are separated by something else, you need the -t option to specify the separator.
Given example file a
Line 2 and 3 have the same third column, but here the sort key is from the third column to the end of line, so -u retains both. ␠ca␠d sorts before ␠c␠c because spaces are ignored in the first pass in my locale, cad sorts before cc .
Above only one is retained for those where the 3rd column is ␠c . Note how the one with ␠␠c (2 leading spaces) is retained.
See how the order of a b c d and a c c c are reversed. In the first case, because ␠c␠c sorts before ␠c␠d , in the second case because the sort key is the same ( ␠c ), the last resort comparison that compares the lines in full puts a b c d before a c c c .
Once we ignore the blanks, the sort key for the first 3 lines is the same ( c ), so they are sorted by the last resort comparison.
In the C locale, ␠␠c sorts before ␠c as there is only one pass there where characters (then single bytes) sort based on their code point value (where space has a lower code point than c ).
Sort by multiple columns in bash
I have a file with 2 columns, «Name» and «Age», looking like this:
I will sort by the first column in alphabetical order, using sort -t ‘,’ -k1,1 filename.txt , but if there are same names, I want the 2nd column to be sorted in the reversed way of how they were in the original file, like this:
4 Answers 4
Read file from back, sort by the first column and -s to preserve order in case of same value
Explain: -t is to specify the field-separator, -k can be used to specify the start and stop position of field, and we could add a single letter OPTS for that field for ordering, for example r means to reverse the result of comparisons.
Wops it seems I misunderstood your problem. I cannot find of a magic command, but a little script might do the job:
- first we assemble the sorted list of names: $names_sorted .
- next (assuming the names do not contain white-spaces), we grep each name from the original list and revert that order with the command tac
Sort by third column leaving first and second column intact in Linux?
I need to sort a flat file by third column leaving first column intact [First column is already sorted] (in linux). (second column may change)
I tried several sorting options but I could sort only by second column but not third.
Can someone please help ?
1 Answer 1
This will sort with the 1st field as primary key, and the 3rd field as secondary key splitting the line into fields by :
Details:
data.txt contains the 4 lines from your post.
You can specify multiple fields as sorting keys, see the man page
-k1,1 means sort on the first field (start at field 1 and end at field 1, otherwise it would continue using the rest of the line for determining the sort)
-k3 means sort on the 3rd field as secondary key. Since there are no other fields behind it is not necessary to specify -k3,3 but it wouldn’t hurt either.
-t: means delimit fields in lines with the : character, otherwise blank is used by default
More information see this SO question Sorting multiple keys with Unix sort and the sort man page
Команда 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:
computer
data
debian
laptop
LAPTOP
mouse
RedHat
Теперь строчка laptop не повторяется.
6. Сортировка по нескольким полям
Мы можем сортировать данные по нескольким полям. Например, отсортируем вывод ls по второму первично и вторично девятому полях:
ls -l | sort -t «,» -nk2,5 -k9
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. Если у вас остались вопросы — спрашивайте в комментариях!