cut is an Unix/Linux command used to cut a sections from each line of files. The default cut command print selected parts of lines from each FILE to standard output. In simple words cut command extract the slices of a line from file.
Syntax:
cut OPTION... [FILE]...
For the examples we are using /etc/passwd file. All the rows are stored in below format with colon (:) separated. We use -f to specify field number and -d for delimiter (separator).
cut command examples in Linux
- Cut first field from all lines – Use
-f
option followed by the filed numbers to cut content from files. Where the filed separate is defined with-d
delimiter.cut -d":" -f1 /etc/passwd
root bin daemon adm lp sync shutdown haltAlso cut can be run on piped output of another command which makes it more flexible to use.
cat /etc/passwd | cut -d":" -f1
- Select multiple fields from file – you can also specify multiple field names with the comma 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 - Define ranges with filed – Instead of defining all filed numbers, you can specify field ranges on command line. A range is defined with hyphen
-
.cut -d":" -f1-4 /etc/passwd
cut -d":" -f3-5 /etc/passwd
cut -d":" -f2-4,6,10 /etc/passwd
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.
- Select all fields except one – 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
- Selecting single character’s from file – Instead of selecting fields, you can also cut characters from file using
-c
parameter followed by numbers.For example to cut first character from each line, type:
cut -c1 /etc/passwd
r b d a l s sSimilarly 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
Conclusion
In this tutorial you have learned about uses of cut command in Linux with useful examples.
Leave a Reply