当前位置:网站首页>Example of using the cut command

Example of using the cut command

2022-08-09 06:33:00 qq_36412526

The

cut command is used for text processing.You can use this command to extract a portion of text from a file by selecting a column

Options for the cut command

Cut basic syntax:

cut OPTION... [FILE]...

Options:

-f : By specifying which field to extract.The cut command uses "TAB" as the default field separator.
-d : "TAB" is the default delimiter, use this option to change to other delimiters.
--complement : This option is used to exclude the specified field.
--output-delimiter : Change the delimiter for output content.

How to split

The most common options for cut are the combination of -d and -f.It basically extracts content based on a specific delimiter and the fields listed.

The following code uses only delimiters: prints the first field of each line in the /etc/passwd file.

[email protected]:~# cut -d ':' -f 1 /etc/passwdrootdaemonbinsyssyncgamesmanlpmailnewsuucpproxywww-databackuplistircgnats

The following code extracts the first and sixth fields from the /etc/passwd file:

[email protected]:~# grep '/bin/bash' /etc/passwd| cut -d ':' -f 1,6root:/rootforlinx:/home/forlinxybtxr:/home/ybtxr

To display the range of fields, specify the start and end fields separated by - as follows:

[email protected]:~# grep '/bin/bash' /etc/passwd|cut -d ':' -f 1-4,6,7root:x:0:0:/root:/bin/bashforlinx:x:1000:1000:/home/forlinx:/bin/bashybtxr:x:1001:1001:/home/ybtxr:/bin/bash

Exclude specified fields

In the code below, print all fields except the second field in the /etc/passwd file:

[email protected]:~# grep '/bin/bash' /etc/passwd|cut -d ':' --complement-f 2root:0:0:root:/root:/bin/bashforlinx:1000:1000:A40i,,,:/home/forlinx:/bin/bashybtxr:1001:1001:,,,:/home/ybtxr:/bin/bash

How to specify a delimiter for output content

To specify the output delimiter, use the --output-delimiter option.The input delimiter is specified by the -d option, by default the output delimiter is the same as the input delimiter.
Let's take a look at what it looks like without the --output-delimiter option:

[email protected]:~# cut -d ':' -f1,7 /etc/passwd|sortavahi-autoipd:/bin/falseavahi:/bin/falsebackup:/bin/shbin:/bin/shcolord:/bin/false

Now use the --output-delimiter option, the output delimiter is separated by ' ' space, and see what it looks like:

[email protected]:~# cut -d ':' -f1,7 --output-delimiter=' ' /etc/passwd|sortavahi-autoipd /bin/falseavahi /bin/falsebackup /bin/shbin /bin/sh

Summary

A limitation of the

cut command is that it does not support specifying multiple characters as delimiters.Multiple spaces are treated as multiple field separators and the tr command must be used to get the desired output.

原网站

版权声明
本文为[qq_36412526]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090628552476.html