Sort linux по убыванию

Sort linux по убыванию

Библиотека сайта rus-linux.net

-c Проверить, является ли (единственный) исходный файл уже отсортированным. На стандартный вывод ничего не выдается. В стандартный протокол выводится соответствующее сообщение только в случае нарушения упорядоченности строк.

-m Только слияние исходных файлов, которые предполагаются отсортированными.

-u Опция уникальности: из всех совпадающих строк выводить только одну.

-o выходной_файл Результат направляется не на стандартный вывод, а в выходной_файл, который может совпадать с одним из исходных.

-yкилобайт Количество дополнительной памяти, используемой командой sort, существенно влияет на скорость ее работы. Если опция -y отсутствует, sort начинает работу, используя область памяти некоторого стандартного размера, а в случае необходимости запрашивает дополнительную память. Если опция -y задана с аргументом, команда sort начинает работу, используя указанное число килобайт памяти, если только не нарушены ограничения сверху или снизу; в этом случае используется соответствующее крайнее значение. Таким образом, указание -y0 гарантирует использование минимального объема памяти. Опция -y без аргумента задает область памяти максимального размера.

-zдлина Во время сортировки запоминается размер самой длинной строки, так что для фазы слияния команда sort может отвести буфер нужного размера. Если, в силу действия опций -c или -m, фаза сортировки пропускается, используется некоторый стандартный размер. Наличие строк, превышающих по длине буфер, приводит к аварийному завершению команды. Задание заведомо достаточной длины гарантирует нормальное выполнение слияния.

Следующие опции позволяют выбрать нужный способ сравнения: -d «Словарный» порядок: при сравнении являются значимыми только буквы, цифры, пробелы и знаки табуляции.

-f Преобразовывать малые буквы в большие.

-i При нечисловых сравнениях игнорировать символы с (восьмеричными) кодами, не лежащими в пределах 040-0176.

-n Числовое сравнение. Начальные пробелы отбрасываются, затем цифровые цепочки символов, содержащие быть может знак минус и десятичную точку, сравниваются как числа. Эта опция включает опцию -b (см. ниже). Отметим, что опция -b действует только на ключи сортировки с наложенными ограничениями.

-r Заменить результат сравнения на противоположный.

Если опции, задающие способ сравнения, указаны до ограничений на ключи сортировки, то они применяются глобально ко всем ключам. Если же соответствующие флаги ассоциированы с определенными ключами сортировки (см. ниже), они воздействуют только на «свои» ключи.

Полем называется минимальная последовательность символов, за которой следует разделитель полей или перевод строки. По умолчанию символом-разделителем считается пробел или символ табуляции. Пробелы и табуляции сразу вслед за разделителем (если они есть) принадлежат следующему полю. Все пробелы в начале строки входят в первое поле. На трактовку разделителей влияют следующие опции: -b Игнорировать начальные пробелы при определении начала и конца ключей сортировки. Если опция -b указана перед первым аргументом +позиция_1, она действует на все ключи с наложенными ограничениями. Флаг b можно связать и с отдельными ключами сортировки (см. ниже).

Читайте также:  Kali linux windows server

-tразделитель Использовать заданный символ как разделитель полей. Разделитель не является частью поля (хотя и может входить в ключ сортировки). Каждое вхождение разделителя является значимым, то есть два рядом стоящих разделителя ограничивают пустое поле.

При наложении ограничения на ключ сортировки указывается позиция начала ключа (+позиция_1) и позиция сразу за концом ключа (-позиция_2). Если опция -позиция_2 отсутствует, ключ занимает весь остаток строки.

Позиция_1 и позиция_2 задаются как пара m.n, возможно, с последующими флагами bdfiMnr. Начальная позиция задается как +m.n, что означает (n+1)-ый символ в (m+1)-ом поле (поля и символы нумеруются с единицы). Отсутствие .n означает .0, то есть первый символ (m+1)-го поля. Если указан флаг b, то n отсчитывается от первого непробела в (m+1)-ом поле; +m.0b означает первый непробел в (m+1)-ом поле.

Позиция за концом ключа записывается как -m.n, что означает (n+1)-ый символ (включая разделители) после последнего символа m-го поля. Если .n опущено, то подразумевается .0, то есть разделитель после m-го поля. Если указан флаг b, то n отсчитывается от первого непробела в (m+1)-ом поле.

Если указано несколько ключей сортировки, то более поздние используются только в случае равенства более ранних. Если значения ключей сортировки двух строк совпадают, строки упорядочиваются с учетом всех символов.

    Отсортировать файл f1, используя в качестве ключа второе поле:

Источник

10 Useful Examples of the Sort Command in Linux

Sort command in Linux is used for sorting the contents of the text files. This tutorial shows you some basic examples of the sort command.

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.

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.

Examples of the sort command

Sort Command Linux

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:

MX Linux Manjaro Mint elementary Ubuntu

Now if you use sort command on it:

Читайте также:  Поиск через командную строку linux

Here’s the alphabetically sorted output:

elementary Manjaro Mint MX Linux Ubuntu

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.

1. MX Linux 4. elementary 2. Manjaro 5. Ubuntu 3. Mint

After sorting, the result is:

1. MX Linux 2. Manjaro 3. Mint 4. elementary 5. Ubuntu

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.

1 5 10 3 5 2 60 23 432 21

Now, if I use the sort command without any options, here’s what I get:

1 10 2 21 23 3 432 5 5 60

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:

1 2 3 5 5 10 21 23 60 432

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:

5. Ubuntu 4. elementary 3. Mint 2. Manjaro 1. MX Linux

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:

4. elementary 1. MX Linux 2. Manjaro 5. Ubuntu 3. Mint

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:

March Feb February April August July June November October December May September 1 4 3 6 01/05/19 01/10/19 02/06/18

Let’s sort it by months using the -M option:

Here’s the output you’ll see:

01/05/19 01/10/19 02/06/18 1 3 4 6 Jan Feb February March April May June July August September October November December

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.

Читайте также:  Ultimate boot cd linux

Caution: If you try to direct your sorted data to the same file, it will erase the contents of your file.

sort filename.txt -n > filename_sorted.txt

If you use cat command on the output file, this will be its contents:

1. MX Linux 2. Manjaro 3. Mint 4. elementary 5. Ubuntu

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.

1. MX Linux 100 2. Manjaro 400 3. Mint 300 4. elementary 500 5. Ubuntu 200

This will sort the text on the second column in alphabetical order:

4. elementary 500 2. Manjaro 400 3. Mint 300 1. MX Linux 100 5. Ubuntu 200

This will sort the text by the numerals on the third column.

1. MX Linux 100 5. Ubuntu 200 3. Mint 300 2. Manjaro 400 4. elementary 500

Same as the above command just that the sort order has been reversed.

4. elementary 500 2. Manjaro 400 3. Mint 300 5. Ubuntu 200 1. MX Linux 100

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.

1. MX Linux 2. Manjaro 3. Mint 4. elementary 5. Ubuntu 1. MX Linux 2. Manjaro 3. Mint 4. elementary 5. Ubuntu 1. MX Linux 2. Manjaro 3. Mint 4. elementary 5. Ubuntu
sort filename.txt -u > filename_duplicates.txt

Here’s the output files sorted and without duplicates.

1. MX Linux 2. Manjaro 3. Mint 4. elementary 5. Ubuntu 

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:

alpha alPHa Alpha ALpha beta Beta BEta BETA

10. Sort by human numeric values [option -h]

This option allows the comparison of alphanumeric values like 1k (i.e. 1000).

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?

Источник

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