- Команда Cut в Linux с примерами
- Linux Cut Command with Examples
- В этом руководстве мы покажем вам, как использовать cut команду, на практических примерах и подробных объяснениях наиболее распространенных опций.
- Как использовать cut команду
- Как вырезать по полю
- Как резать на основе разделителя
- Как дополнить выбор
- Как указать выходной разделитель
- Как вырезать из байтов и символов
- Примеры
- Получить список всех пользователей
- Посмотреть 10 наиболее часто используемых команд
- Вывод
- Linux Cut Command with Practical Examples
- Cut Command and Syntax
- Cut Options
- How to cut by delimiter
- How to complement the output selection
- How to specify an output delimiter
- How to cut by c haracters
- How to cut by bytes
- Some practical cut examples
- Conclusion
- How to cut by c haracters
- How to cut by bytes
- Some practical cut examples
- Conclusion
- cut command in Linux with examples
Команда Cut в Linux с примерами
Linux Cut Command with Examples
В этом руководстве мы покажем вам, как использовать cut команду, на практических примерах и подробных объяснениях наиболее распространенных опций.
В системах Linux и Unix доступно множество утилит, позволяющих обрабатывать и фильтровать текстовые файлы. cut утилита командной строки, которая позволяет вырезать части строк из указанных файлов или данных по конвейеру и выводить результат в стандартный вывод. Его можно использовать для вырезания частей строки по разделителю, позиции байта и символу.
Как использовать cut команду
Синтаксис cut команды следующий:
Параметры, указывающие cut , использовать ли разделитель, позицию байта или символ при вырезании выделенных частей, выглядят следующим образом:
- -f ( —fields=LIST ) — Выберите, указав поле, набор полей или диапазон полей. Это наиболее часто используемый вариант.
- -b ( —bytes=LIST ) — Выберите, указав байт, набор байтов или диапазон байтов.
- -c ( —characters=LIST ) — Выберите, указав символ, набор символов или диапазон символов.
Вы можете использовать один и только один из вариантов, перечисленных выше.
- -d ( —delimiter ) — Укажите разделитель, который будет использоваться вместо разделителя «TAB» по умолчанию.
- —complement — дополнить выбор. При использовании этого параметра cut отображаются все байты, символы или поля, кроме выбранного.
- -s ( —only-delimited ) — по умолчанию cut печатает строки, которые не содержат символов-разделителей. Когда эта опция используется, cut не печатать строки, не содержащие разделителей.
- —output-delimiter — По умолчанию cut используется входной разделитель в качестве выходного разделителя. Эта опция позволяет вам указать другую строку выходного разделителя.
Команда cut может принимать ноль или более входных имен FILE. Если не FILE указано, или когда FILE есть — , cut будет читать со стандартного ввода.
LIST Аргумент , переданный -f , -b и -c варианты могут быть целым числом, несколько целых чисел , разделенных запятыми, диапазон целых чисел или нескольких диапазонов целочисленных разделенных запятыми. Каждый диапазон может быть одним из следующих:
- N N-е поле, байт или символ, начиная с 1.
- N- от N-го поля, байта или символа до конца строки.
- N-M от N-го до M-го поля, байта или символа.
- -M от первого до M-го поля, байта или символа.
Как вырезать по полю
Чтобы указать поля, которые должны быть вырезаны, вызовите команду с -f опцией. Если не указан, по умолчанию используется разделитель «TAB».
В приведенных ниже примерах мы будем использовать следующий файл. Поля разделены вкладками.
Например, для отображения 1-го и 3-го полей вы должны использовать:
Или, если вы хотите отобразить с 1-го по 4-е поле:
Как резать на основе разделителя
Чтобы вырезать на основе разделителя, вызовите команду с -d параметром, а затем разделитель, который вы хотите использовать.
Например, чтобы отобразить 1-е и 3-е поля, используя «:» в качестве разделителя, введите:
Вы можете использовать любой отдельный символ в качестве разделителя. В следующем примере мы используем символ пробела в качестве разделителя и печатаем 2-е поле:
Как дополнить выбор
Для дополнения списка полей выбора используйте —complement опцию. Это напечатает только те поля, которые не выбраны с -f опцией.
Следующая команда напечатает все поля кроме 1-го и 3-го:
Как указать выходной разделитель
Чтобы указать выходной разделитель, используйте —output-delimiter опцию. Например, чтобы установить для _ вас выходной разделитель , используйте:
Как вырезать из байтов и символов
Прежде чем идти дальше, давайте сделаем различие между байтами и символами.
Один байт составляет 8 битов и может представлять 256 различных значений. Когда был установлен стандарт ASCII, в нем были учтены все буквы, цифры и символы, необходимые для работы с английским языком. Таблица символов ASCII имеет 128 символов, и каждый символ представлен одним байтом. Когда компьютеры стали доступны во всем мире, технологические компании начали вводить новые кодировки символов для разных языков. Для языков, содержащих более 256 символов, простое сопоставление 1 к 1 было невозможно. Это приводит к различным проблемам, таким как совместное использование документов или просмотр веб-сайтов, и был необходим новый стандарт Unicode, который может работать с большинством мировых систем письма. UTF-8 был создан для решения этих проблем. В UTF-8 не все символы представлены 1 байтом. Символы могут быть представлены от 1 байта до 4 байтов.
Опция -b ( —bytes ) указывает команде вырезать секции из каждой строки, заданной заданными позициями байтов.
В следующих примерах мы используем ü символ, который занимает 2 байта.
Выберите 5-й байт:
Выберите 5-й, 9-й и 13-й байты:
Выберите диапазон от 1-го до 5-го байта:
На момент написания этой статьи версия пакета cut в GNU coreutils не имела возможности обрезать по символам. При использовании -c параметра cut ведет себя так же, как при использовании -b параметра.
Примеры
Команда cut обычно используется в сочетании с другими командами через трубопровод. Вот несколько примеров:
Получить список всех пользователей
Выходные данные getent passwd команды передаются в cut , который печатает 1-е поле, используя в : качестве разделителя.
Посмотреть 10 наиболее часто используемых команд
В следующем примере cut используется для удаления первых 8 байтов из каждой строки history вывода команды.
Вывод
cut Команда используется для отображения выбранных полей из каждой строки заданных файлов или стандартного ввода.
Хотя это очень полезно, cut имеет некоторые ограничения. Он не поддерживает указание более одного символа в качестве разделителя и не поддерживает несколько разделителей.
Источник
Linux Cut Command with Practical Examples
The cut command is used in Linux and Unix systems to cut parts and sections from each line of a file and write the result to standard output. It can be used to cut parts of a line by byte position, character and field (delimiter).
In this tutorial, we learn Linux cut command with some practical examples you can use in your day to day command line activities.
Cut Command and Syntax
The basic syntax for the cut command is as follows:
Let’s check cut options and without any option cut command won’t work.
Cut Options
-f : Extract by specifying a field. Cut command uses ‘TAB’ as the default field delimiter.
-d : ‘Tab’ is the default delimiter and using this option you can use specific delimiter.
-b : To extract by specifying a byte. The range of bytes can also be specified.
-c : To cut by character. This can be a list of numbers separated comma or a range of numbers separated by a hyphen (-).
–complement : This will complement the selection
–output-delimiter : To change the output delimiter use the option -output-delimiter=’delimiter’.
—only-delimited : Cut will not print lines not containing delimiters
We will use the following text file named ‘content.txt’ and /etc/passwd file throughout this tutorial to illustrate our examples.
How to cut by delimiter
The most commonly used cut option is a combination of -d and -f . It will basically extract content based on specific delimiter and listed fields.
For example the following prints only the 1st field of each line from ‘/etc/passwd’ file using the delimiter (:).
The following example where we use space (» «) as delimiter and cut the 1st field from the file named ‘content.txt’.
This example, extracts more than one field from a specific file. Here we extract 1st and 6th field using colon (:) delimiter from the file ‘/etc/passwd’ which has the string ‘/bin/bash’:
To display the range of fields, specify start field and end field separated by hypen (-) as shown below:
How to complement the output selection
To complement the selection field list use —complement option. This option used where to select all fields except the specified fields.
In the following example command prints all the fields except the 2nd field in the from ‘/etc/passwd’ file:
How to specify an output delimiter
To specify the output delimiter use the —output-delimiter option. Input delimiter is specified by -d option and by default output delimiter is the same as input delimiter.
Lets first check out the output without using output delimiter as follows:
Now I have added —output-delimiter option and input delimiter colon (:) is replaced with output delimiter ‘SPACE» as follows:
Let’s check another example, here we use output delimiter to print on each field in a new line.
Here we use —output-delimiter as $’\n’ which indicates a new line.
Check the output:
How to cut by c haracters
The -c (column) option is used for cutting by character position. Remember that ‘TABS» and ‘Spaces’ are also treated as characters.
To print 1st character from each line from the file named content.txt, use below:
In the following example we will display character 1 through 7 (range) of each line from the file:
Let’s check how to select columns by either specific start or end position.
To extract columns from 2nd character to last character:
To extract columns from 1st character to 4th character:
How to cut by bytes
Use the -b option to select out a portion of a line by specifying a byte position by numbers separated by comma (,). Using hyphen you can specify a range of bytes.
The following example cut from 1st, 2nd and 3rd bytes from the file named ‘content.txt’:
We can also list with ranges using the below command:
Some practical cut examples
Cut is most practical used with a combination of different Linux or Unix commands.
For example, you want to extract ‘USER’, ‘PID’ and «COMMAND» using ps command:
Let’s take another example to extract ‘total’, ‘used’ and ‘free’ value of memory and save to a text file using multiple command:
Conclusion
The cut command can be piped with many other Linux or Unix commands. It can be piped with one or more filters for additional text processing.
One of the limitations of cut command is it doesn’t support specifying more than one character as a delimiter. Multiple blanks are counted as multiple field separators and have to use tr command before cut to get the desired output.
How to cut by c haracters
The -c (column) option is used for cutting by character position. Remember that ‘TABS» and ‘Spaces’ are also treated as characters.
To print 1st character from each line from the file named content.txt, use below:
In the following example we will display character 1 through 7 (range) of each line from the file:
Let’s check how to select columns by either specific start or end position.
To extract columns from 2nd character to last character:
To extract columns from 1st character to 4th character:
How to cut by bytes
Use the -b option to select out a portion of a line by specifying a byte position by numbers separated by comma (,). Using hyphen you can specify a range of bytes.
The following example cut from 1st, 2nd and 3rd bytes from the file named ‘content.txt’:
We can also list with ranges using the below command:
Some practical cut examples
Cut is most practical used with a combination of different Linux or Unix commands.
For example, you want to extract ‘USER’, ‘PID’ and «COMMAND» using ps command:
Let’s take another example to extract ‘total’, ‘used’ and ‘free’ value of memory and save to a text file using multiple command:
Conclusion
The cut command can be piped with many other Linux or Unix commands. It can be piped with one or more filters for additional text processing.
One of the limitations of cut command is it doesn’t support specifying more than one character as a delimiter. Multiple blanks are counted as multiple field separators and have to use tr command before cut to get the desired output.
Источник
cut command in Linux with examples
The cut command in UNIX is a command for cutting out the sections from each line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field. Basically the cut command slices a line and extracts the text. It is necessary to specify option with command otherwise it gives error. If more than one file name is provided then data from each file is not precedes by its file name.
Syntax:
Let us consider two files having name state.txt and capital.txt contains 5 names of the Indian states and capitals respectively.
Without any option specified it displays error.
Options and their Description with examples:
1. -b(byte): To extract the specific bytes, you need to follow -b option with the list of byte numbers separated by comma. Range of bytes can also be specified using the hyphen(-). It is necessary to specify list of byte numbers otherwise it gives error. Tabs and backspaces are treated like as a character of 1 byte.
It uses a special form for selecting bytes from beginning upto the end of the line:
2. -c (column): To cut by character use the -c option. This selects the characters given to the -c option. This can be a list of numbers separated comma or a range of numbers separated by hyphen(-). Tabs and backspaces are treated as a character. It is necessary to specify list of character numbers otherwise it gives error with this option.
Syntax:
Here,k denotes the starting position of the character and n denotes the ending position of the character in each line, if k and n are separated by “-” otherwise they are only the position of character in each line from the file taken as an input.
Above cut command prints second, fifth and seventh character from each line of the file.
Above cut command prints first seven characters of each line from the file.
Cut uses a special form for selecting characters from beginning upto the end of the line:
3. -f (field): -c option is useful for fixed-length lines. Most unix files doesn’t have fixed-length lines. To extract the useful information you need to cut by fields rather than columns. List of the fields number specified must be separated by comma. Ranges are not described with -f option. cut uses tab as a default field delimiter but can also work with other delimiter by using -d option.
Note: Space is not considered as delimiter in UNIX.
Syntax:
Like in the file state.txt fields are separated by space if -d option is not used then it prints whole line:
If -d option is used then it considered space as a field separator or delimiter:
4. –complement: As the name suggests it complement the output. This option can be used in the combination with other options either with -f or with -c.
5. –output-delimiter: By default the output delimiter is same as input delimiter that we specify in the cut with -d option. To change the output delimiter use the option –output-delimiter=”delimiter”.
Here cut command changes delimiter(%) in the standard output between the fields which is specified by using -f option .
6. –version: This option is used to display the version of cut which is currently running on your system.
Applications of cut Command
1. How to use tail with pipes(|): The cut command can be piped with many other commands of the unix. In the following example output of the cat command is given as input to the cut command with -f option to sort the state names coming from file state.txt in the reverse order.
It can also be piped with one or more filters for additional processing. Like in the following example, we are using cat, head and cut command and whose output is stored in the file name list.txt using directive(>).
Thanks Saloni Gupta for providing more examples.
Источник