- Команда sort в Linux
- Синтаксис
- Опции
- Примеры использования sort
- 1. Сортировка
- 2. Обратная сортировка
- 3. Сортировка по колонке
- 4. Сортировка по номеру
- 5. Удаление дубликатов
- 6. Сортировка по нескольким полям
- Sort based on the third column
- 6 Answers 6
- 10 Useful Examples of the Sort Command in Linux
- Sort command in Linux
- Examples of the sort command
- 1. Sort in alphabetical order
- 2. Sort on numerical value [option -n]
- 3. Sort in reverse order [option -r]
- 4. Random sort [option -R]
- 5. Sort by months [option -M]
- 6. Save the sorted results to another file
- 7. Sort Specific Column [option -k]
- 8. Sort and remove duplicates [option -u]
- 9. Ignore case while sorting [option -f]
- 10. Sort by human numeric values [option -h]
Команда 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. Если у вас остались вопросы — спрашивайте в комментариях!
Источник
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 ).
Источник
10 Useful Examples of the Sort Command in Linux
Sort command in Linux
The sort command arranges text lines in useful ways. This simple tool can help you quickly sort information from the command line.
Syntax
You should note a few thing:
- When you use sort without any options, the default rules are enforced. It helps to understand the default rules to avoid unexpected outcomes.
- When using sort, your original data is safe. The results of your input are displayed on the command line only. However, you can specify output to a separate file if you wish. More on that later.
- Sort was originally designed for use with ASCII characters. I did not test for this, but it is possible that different encodings may produce unexpected results.
The default rules in the sort command
These are the default rules when using sort. The first few examples will clarify how these priorties are managed. Then we will look at specialized options.
- numbers > letters
- lowercase > uppercase
Examples of the sort command
Let me show you some examples of sort command that you can use in various situations.
1. Sort in alphabetical order
The default sort command makes it easy to view information in alphabetical order. No options are necessary and even with mixed-case entries, A-Z sorting works as expected.
I am going to use a sample text file named filename.txt and if you view the content of the file, this is what you’ll see:
Now if you use sort command on it:
Here’s the alphabetically sorted output:
2. Sort on numerical value [option -n]
Let’s take the same list we used for the previous example and sort in numerical order. In case you were wondering, the list reflects the most popular Linux distributions (July, 2019) according to distrowatch.com.
I will modify the contents of the file so that the items are numbered, but out of order as shown below.
After sorting, the result is:
Looks good, right? Can you rely on this method to arrange your data accurately, though? Probably not. Let’s look at another example to find out why.
Here’s my new sample text:
Now, if I use the sort command without any options, here’s what I get:
NOTE: Numbers are sorted by their leading characters only.
When you add the -n option, the numerical value of the string is now being evaluated rather than only the first character. Now, you can see below that our list is properly sorted.
Now you’ll have the correctly sorted output:
3. Sort in reverse order [option -r]
For this one, I am going to use our distro list again. The reverse function is self-explanatory. It will reverse the order of whatever content you have in your file.
And here you have the output text in reverse order:
4. Random sort [option -R]
If you accidentally mashed your shift key while attempting the reverse function, you might have gotten some strange results. -R rearranges output in randomized order.
Here’s the randomly sorted output:
5. Sort by months [option -M]
Sort also has built in functionality to arrange by month. It recognizes several formats based on locale-specific information. I tried to demonstrate some unqiue tests to show that it will arrange by date-day, but not year. Month abbreviations display before full-names.
Here is the sample text file in this example:
Let’s sort it by months using the -M option:
Here’s the output you’ll see:
6. Save the sorted results to another file
As I mentioned earlier, sort does not change the original file by default. If you need to save the sorted content, it can be done.
For this example, I’ve created a new file where I want the sorted information to be printed and saved with the name filename_sorted.txt.
Caution: If you try to direct your sorted data to the same file, it will erase the contents of your file.
If you use cat command on the output file, this will be its contents:
7. Sort Specific Column [option -k]
If you have a table in your file, you can use the -k option to specify which column to sort. I added some arbitrary numbers as a third column and will display the output sorted by each column. I’ve included several examples to show the variety of output possible. Options are added following the column number.
This will sort the text on the second column in alphabetical order:
This will sort the text by the numerals on the third column.
Same as the above command just that the sort order has been reversed.
8. Sort and remove duplicates [option -u]
If you have a file with potential duplicates, the -u option will make your life much easier. Remember that sort will not make changes to your original data file. I chose to create a new file with just the items that are duplicates. Below you’ll see the input and then the contents of each file after the command is run.
Here’s the output files sorted and without duplicates.
9. Ignore case while sorting [option -f]
Many modern distros running sort will implement ignore case by default. If yours does not, adding the -f option will produce the expected results.
Here’s the output where cases are ignored by the sort command:
10. Sort by human numeric values [option -h]
This option allows the comparison of alphanumeric values like 1k (i.e. 1000).
Here’s the sorted output:
I hope this tutorial helped you get the basic usage of the sort command in Linux. Sort command is often used in conjugation with the uniq command in Linux for uniquely sorting text files.
If you have some cool sort trick, why not share it with us in the comment section?
Источник