Home > Article > Operation and Maintenance > Introduction to the usage of Linux cut command
Linux cut command is used to extract file content based on fields. Text files don't have rows/columns like databases, sometimes we just need a single column of data. Cut recognized columns based on delimiter (eg: colon ':', semicolon ';', comma ', ', etc.).
For the following example, we use the /etc/passwd file. All lines are stored in the following format, separated by colon (:) as follows. We use -f to specify the field number and -d as the delimiter.
According to the picture above, this file has 7 fields. cut also supports obtaining values on a character basis suing -c command line switch. Let's look at the following example, using the /etc/passwd file.
1. Select a single field from the file:
For example, we need the list of usernames in the /etc/passwd file. We know that the first column stores the username and the entire file is separated by colon (:).
#cut -d“:” - f1 </ etc / passwd root bin daemon adm lp sync shutdown halt
We can also use the pipe "|" to pass the file content as input to the cut command, as shown below-
#cat / etc / passwd | cut -d“:” - f1
2. Select multiple columns from the file :
We can specify multiple field names separated by commands, as shown in the example below, only the 1st, 2nd and 7th fields will be displayed.
# cut -d":" -f1,2,7 < /etc/passwd root:x:/bin/bash bin:x:/sbin/nologin daemon:x:/sbin/nologin adm:x:/sbin/nologin lp:x:/sbin/nologin sync:x:/bin/sync shutdown:x:/sbin/shutdown halt:x:/sbin/halt mail:x:/sbin/nologin uucp:x:/sbin/nologin
We can also specify the range of the column with a hyphen (-) on the field along with both options as in the example command below.
The first command will select the 1st, 2nd, 3rd and 4th fields.
The second command will select the 3rd, 4th and 5th fields.
The last command will display the 2nd, 3rd, 4th, 6th and 10th fields.
# cut -d":" -f1-4 < /etc/passwd # cut -d":" -f3-5 < /etc/passwd # cut -d":" -f2-4,6,10 < /etc/passwd
To get the values of all columns except one, you need to use the following command. For example, if we need to select all columns instead of 6 columns.
# cut -d":" --complement -s -f6 < /etc/passwd
3. Select a single character from the file
In addition to fields, we can also select values from the file based on a single character, which is not required when using characters. Specify the separator character.
#cut -c1 </ etc / passwd r b d a l s s
Similarly, we can also specify multiple comma-separated characters or character ranges.
#cut -c1,2,3,6,7 </ etc / passwd #cut -c1-3,6,7 </ etc / passwd
This article has ended here. For more other exciting content, you can pay attention to the Linux Tutorial Video column of the PHP Chinese website!
The above is the detailed content of Introduction to the usage of Linux cut command. For more information, please follow other related articles on the PHP Chinese website!