Linux find sort by name

Команда find в Linux – мощный инструмент сисадмина

Иногда критически важно быстро найти нужный файл или информацию в системе. Порой можно ограничиться стандартами функциями поиска, которыми сейчас обладает любой файловый менеджер, но с возможностями терминала им не сравниться.

Команда find – это невероятно мощный инструмент, позволяющий искать файлы не только по названию, но и по:

  • Дате добавления.
  • Содержимому.
  • Регулярным выражениям.

Данная команда будет очень полезна системным администраторам для:

  • Управления дисковым пространством.
  • Бэкапа.
  • Различных операций с файлами.

Команда find в Linux производит поиск файлов и папок на основе заданных вами критериев и позволяет выполнять действия с результатами поиска.

Синтаксис команды find:

  • directory-to-search (каталог поиска) – это отправной каталог, с которой find начинает поиск файлов по всем подкаталогам, которые находятся внутри. Если не указать путь, тогда поиск начнется в текущем каталоге;
  • criteria (критерий) – критерий, по которым нужно искать файлы;
  • action (действие) – что делать с каждым найденным файлом, соответствующим критериям.

Поиск по имени

Следующая команда ищет файл s.txt в текущем каталоге:

  • . (точка) – файл относится к нынешнему каталогу
  • -name – критерии по которым осуществляется поиск. В данном случае поиск по названию файла.

В данном случае критерий -name учитывает только символы нижнего регистра и файл S.txt не появиться в результатах поиска. Чтобы убрать чувствительность к регистру необходимо использовать –iname.

Для поиска всех изображений c расширением .png нужно использовать шаблон подстановки *.png:

Можно использовать название каталога для поиска. Например, чтобы с помощью команды find найти все png изображения в каталоге home:

Если выдает слишком много ошибок в отказе разрешения, тогда можно добавить в конец команды – 2> /dev/null. Таким образом сообщения об ошибках будут перенаправляться по пути dev/null, что обеспечит более чистую выдачу.

Поиск по типу файла

Критерий -type позволяет искать файлы по типу, которые бывают следующих видов:

  • f – простые файлы;
  • d – каталоги;
  • l – символические ссылки;
  • b – блочные устройства (dev);
  • c – символьные устройства (dev);
  • p – именованные каналы;
  • s – сокеты;

Например, указав критерий -type d будут перечислены только каталоги:

Поиск по размеру файла

Допустим, что вам необходимо найти все большие файлы. Для таких ситуаций подойдет критерий -size.

  • «+» — Поиск файлов больше заданного размера
  • «-» — Поиск файлов меньше заданного размера
  • Отсутствие знака означает, что размер файлов в поиске должен полностью совпадать.

В данном случае поиск выведет все файлы более 1 Гб (+1G).

Единицы измерения файлов:

Поиск пустых файлов и каталогов

Критерий -empty позволяет найти пустые файлы и каталоги.

Поиск времени изменения

Критерий -cmin позволяет искать файлы и каталоги по времени изменения. Для поиска всех файлов, измененных за последний час (менее 60 мин), нужно использовать -60:

Таким образом можно найти все файлы в текущем каталоге, которые были созданы или изменены в течение часа (менее 60 минут).

Для поиска файлов, которые наоборот были изменены в любое время кроме последнего часа необходимо использовать +60.

Поиск по времени доступа

Критерий -atime позволяет искать файлы по времени последнего доступа.

Таким образом можно найти файлы, к которым не обращались последние полгода (180 дней).

Читайте также:  Что делать если лагает linux mint

Поиск по имени пользователя

Опция –user username дает возможность поиска всех файлов и каталогов, принадлежащих конкретному пользователю:

Таким образом можно найти все файлы пользователя tisha в каталоге home, а 2>/dev/null сделает выдачу чистой без ошибок в отказе доступа.

Поиск по набору разрешений

Критерий -perm – ищет файлы по определенному набору разрешений.

Поиск файлов с разрешениями 777.

Операторы

Для объединения нескольких критериев в одну команду поиска можно применять операторы:

Например, чтобы найти файлы размером более 1 Гбайта пользователя tisha необходимо ввести следующую команду:

Если файлы могут принадлежать не только пользователю tisha, но и пользователю pokeristo, а также быть размером более 1 Гбайта.

Перед скобками нужно поставить обратный слеш «\».

Действия

К команде find можно добавить действия, которые будут произведены с результатами поиска.

  • -delete — Удаляет соответствующие результатам поиска файлы
  • -ls — Вывод более подробных результатов поиска с:
    • Размерами файлов.
    • Количеством inode.
  • -print Стоит по умолчанию, если не указать другое действие. Показывает полный путь к найденным файлам.
  • -exec Выполняет указанную команду в каждой строке результатов поиска.

-delete

Полезен, когда необходимо найти и удалить все пустые файлы, например:

Перед удалением лучше лишний раз себя подстраховать. Для этого можно запустить команду с действием по умолчанию -print.

Данное действие является особенным и позволяет выполнить команду по вашему усмотрению в результатах поиска.

  • command – это команда, которую вы желаете выполнить для результатов поиска. Например:
    • rm
    • mv
    • cp
  • <> – является результатами поиска.
  • \; — Команда заканчивается точкой с запятой после обратного слеша.

С помощью –exec можно написать альтернативу команде –delete и применить ее к результатам поиска:

Другой пример использования действия -exec:

Таким образом можно скопировать все .jpg изображения в каталог backups/fotos

Заключение

Команду find можно использовать для поиска:

  • Файлов по имени.
  • Дате последнего доступа.
  • Дате последнего изменения.
  • Имени пользователя (владельца файла).
  • Имени группы.
  • Размеру.
  • Разрешению.
  • Другим критериям.

С полученными результатами можно сразу выполнять различные действия, такие как:

  • Удаление.
  • Копирование.
  • Перемещение в другой каталог.

Команда find может сильно облегчить жизнь системному администратору, а лучший способ овладеть ей – больше практиковаться.

Источник

Linux sort command

sort sorts the contents of a text file, line by line.

Overview

sort is a simple and very useful command which will rearrange the lines in a text file so that they are sorted, numerically and alphabetically. By default, the rules for sorting are:

  • Lines starting with a number will appear before lines starting with a letter.
  • Lines starting with a letter that appears earlier in the alphabet will appear before lines starting with a letter that appears later in the alphabet.
  • Lines starting with a lowercase letter will appear before lines starting with the same letter in uppercase.

The rules for sorting can be changed according to the options you provide to the sort command; these are listed below.

Syntax

Options

-b,
—ignore-leading-blanks
Ignore leading blanks.
-d, —dictionary-order Consider only blanks and alphanumeric characters.
-f, —ignore-case Fold lower case to upper case characters.
-g,
—general-numeric-sort
Compare according to general numerical value.
-i, —ignore-nonprinting Consider only printable characters.
-M, —month-sort Compare (unknown) Note

if you are using the join command in conjunction with sort, be aware that there is a known incompatibility between the two programs — unless you define the locale. If you are using join and sort to process the same input, it is highly recommended that you set LC_ALL to C, which will standardize the localization used by all programs.

Checking For Sorted Order

If you just want to check to see if your input file is already sorted, use the -c option:

If your data is unsorted, you will receive an informational message reporting the line number of the first unsorted data, and what the unsorted data is:

Sorting Multiple Files Using The Output Of find

One useful way to sort data is to sort the input of multiple files, using the output of the find command. The most reliable (and responsible) way to accomplish this is to specify that find produces a NUL-terminated file list as its output, and to pipe that output into sort using the —files0-from option.

Normally, find outputs one file on each line; in other words, it inserts a line break after each file name it outputs. For instance, let’s say we have three files named data1.txt, data2.txt, and data3.txt. find can generate a list of these files using the following command:

This command uses the question mark wildcard to match any file that has a single character after the word «data» in its name, ending in the extension «.txt«. It produces the following output:

It would be nice if we could use this output to tell the sort command, «sort the data in any files found by find as if they were all one big file.» The problem with the standard find output is, even though it’s easy for humans to read, it can cause problems for other programs that need to read it in. Because file names can include non-standard characters, so in some cases, this format will be read incorrectly by another program.

The correct way to format find‘s output to be used as a file list for another program is to use the -print0 option when running find. This terminates each file name with the NUL character (ASCII character number zero), which is universally illegal to use in file names. This makes things easier for the program reading the file list, since it knows that any time it sees the NUL character, it can be sure it’s at the end of a file name.

So, if we run the previous command with the -print0 option at the end, like this:

. it will produce the following output:

You can’t see it, but after each file name is a NUL character. This character is non-printable, so it will not appear on your screen, but it’s there, and any programs you pipe this output to (sort, for example) will see them.

Be careful how you word the find command. It’s important to specify -print0 last; find needs this to be specified after the other options.

Okay, but how do we tell sort to read this file list and sort the contents of all those files?

One way to do it is to pipe the find output to sort, specifying the —files0-from option in the sort command, and specify the file as a dash (««), which will read from the standard input. Here’s what the command will look like:

. and it will output the sorted data of any files located by find which matches the pattern data?.txt, as if they were all one file. This example is a very powerful function of sort — give it a try.

Comparing Only Selected Fields Of Data

Normally, sort decides how to sort lines based on the entire line: it compares every character from the first character in a line, to the last one.

If, on the other hand, you want sort to compare a limited subset of your data, you can specify which fields to compare using the -k option.

For instance, if you have an input file data.txt With the following data:

. and you sort it without any options, like this:

. you will receive the following output:

. as you can see, nothing was changed from the original data ordering, because of the numbers at the beginning of the line — which were already sorted. However, if you want to sort based on the names, you can use the following command:

This command will sort the second field, and ignore the first. (The «k» in «-k» stands for «key» — we are defining the «sorting key» used in the comparison.)

Fields are defined as anything separated by whitespace; in this case, an actual space character. Our command above will produce the following output:

. which is sorted by the second field, listing the lines alphabetically by name, and ignoring the numbers in the sorting process.

You can also specify a more complex -k option. The complete positional argument looks like this:

. where POS1 is the starting field position, and POS2 is the ending field position. Each field position, in turn, is defined as:

. where F is the field number and C is the character within that field to begin the sort comparison.

So, let’s say our input file data.txt contains the following data:

. we can sort by seniority if we specify the third field as the sort key:

. this produces the following output:

Or, we can ignore the first three characters of the third field, and sort solely based on title, ignoring seniority:

We can also specify where in the line to stop comparing. If we sort based on only the third-through-fifth characters of the third field of each line, like this:

. sort will see only the same thing on every line: «.De» . and nothing else. As a result, sort will not see any differences in the lines, and the sorted output will be the same as the original file:

Using sort And join Together

sort can be especially useful when used in conjunction with the join command. Normally join will join the lines of any two files whose first field match. Let’s say you have two files, file1.txt and file2.txt. file1.txt contains the following text:

. and file2.txt contains the following:

If you’d like sort these two files and join them, you can do so all in one command if you’re using the bash command shell, like this:

Here, the sort commands in parentheses are each executed, and their output is redirected to join, which takes their output as standard input for its first and second arguments; it is joining the sorted contents of both files and gives results similar to the below results.

comm — Compare two sorted files line by line.
join — Join the lines of two files which share a common field of data.
uniq — Identify, and optionally filter out, repeated lines in a file.

Источник

Читайте также:  Появилось обновить до windows 10
Оцените статью