-->

How to use cut Command in Linux

Author Piyush Gupta

Linux cut command is used for extracting file content on fields basis. text files do not have row/column like databases and some times we need the data of single column only. Cut identified columns on basis of separator (eg: colon ‘:’, semicolon ‘;’, comma ‘,’ etc).
For this example we are taking /etc/passwd file. All the rows are stored as below format with colon (:) separated like below. We use -f to specify field number and -d for delimiter (separator).

As per above screen-cast this file has 7 fields. Cut also support to fetch values on character basis suing -c command line switch. Lets take below examples, for which I am using /etc/passwd file.

1. Select Single Field from File –

For example we need the list of usernames from our /etc/passwd file. We know that first column stored username, Entire file is separated by colon (:).
# cut -d":" -f1  < /etc/passwd

root
bin
daemon
adm
lp
sync
shutdown
halt
We can also use pipeline " | " for passing the file content as input to cut command, like below -
# cat  /etc/passwd | cut -d":" -f1

2. Select Multiple Columns from File -

We can specify multiple field names with command separated, like below example will show the 1'st, 2'nd and 7'th fields only.
# 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 columns with hyphen (-) on fields as well as both option's together like below example commands.
    • Here first command will select 1'st, 2'nd,3'rd and 4'th fields.
    • Second command will select 3'rd, 4'th and 5'th fields.
    • Last command will show 2'nd, 3'rd, 4'th, 6'th and 10'th fields.
# cut -d":" -f1-4 < /etc/passwd
# cut -d":" -f3-5 < /etc/passwd
# cut -d":" -f2-4,6,10 < /etc/passwd
To get values of all columns except one use following command. For example if we need to select all columns but not 6.
# cut -d":" --complement -s -f6 < /etc/passwd

3. Selecting Single Character's from File -

Except fields we can also select values from file on basis of single characters, while using characters we don't need to specify separator.
# cut -c1 < /etc/passwd

r
b
d
a
l
s
s
Similarly fields we can also specify multiple comma separated characters or range of characters.
# cut -c1,2,3,6,7 < /etc/passwd
# cut -c1-3,6,7 < /etc/passwd

No comments:

Post a Comment