cut command in UNIX
cut OPTION... [FILE]...
Introduction
Section titled “Introduction”With no FILE
(or when FILE
is -
), cut
reads from standard input.
It removes sections from each line of files. In other word, it prints selected parts of lines from each FILE
to standard output.
Options
Section titled “Options”The most useful options are:
-c
,--characters=LIST
: select only these characters-d
,--delimiter=DELIM
: useDELIM
instead ofTAB
for field delimiter-f
,--fields=LIST
: select only these fields; also print any line that contains no delimiter character (unless the-s
option is specified)-s
,--only-delimited
: do not print lines not containing delimiters-z
,--zero-terminated
: line delimiter isNUL
, not newline
You can also use cut
command over shell variables using pipe operator.
Examples
Section titled “Examples”my_string="rock,paper,scissor"echo $my_stringrock,paper,scissor
# print from 6th to 10th characterecho $my_string | cut -c 6-10paper
# characters starts at index 1echo $my_string | cut -c 0-10cut: byte/character positions are numbered from 1Try 'cut --help' for more information.
# prints all characters in the indexes separated with commasecho $my_string | cut -c 2,6,9ope
# prints the 2nd field after the comma delimiterecho $my_string | cut -f 2 -d ','paper
# redirect the command to the standard inputcut -c 1,8 -123456789 # write this line and press 'Enter18 # this is the given output
# Press 'Ctrl' + 'D' to exit and get back the control over the shell# or press 'Ctrl' + 'C' to terminate the command
Take a look at User Credentials slice than come back here and learn how to use cut
command to print out name, home directory and login shell for each user in /etc/passwd
file.
# enclose colon sign between single quotes is not mandatory# cut -d ':' -f 1,6,7 /etc/passwdcut -d : -f 1,6,7 /etc/passwdroot:/root:/bin/bashdaemon:/usr/sbin:/usr/sbin/nologinbin:/bin:/usr/sbin/nologinsys:/dev:/usr/sbin/nologin# many other linespit:/home/pit:/bin/bash
# more readable versions# cut -d : -f 1,6,7 /etc/passwd | less# cut -d : -f 1,6,7 /etc/passwd | more
Quotes
Section titled “Quotes”Manual reference: