cut command in UNIX

post hero image

cut OPTION... [FILE]...

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

The most useful options are:

  • -c, --characters=LIST: select only these characters
  • -d, --delimiter=DELIM: use DELIM instead of TAB 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 is NUL, not newline

You can also use cut command over shell variables using pipe operator.

Examples

my_string="rock,paper,scissor"
echo $my_string
rock,paper,scissor

# print from 6th to 10th character
echo $my_string | cut -c 6-10
paper

# characters starts at index 1
echo $my_string | cut -c 0-10
cut: byte/character positions are numbered from 1
Try 'cut --help' for more information.

# prints all characters in the indexes separated with commas
echo $my_string | cut -c 2,6,9
ope

# prints the 2nd field after the comma delimiter
echo $my_string | cut -f 2 -d ','
paper

# redirect the command to the standard input
cut -c 1,8 -
123456789 # write this line and press 'Enter
18 # 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/passwd
cut -d : -f 1,6,7 /etc/passwd
root:/root:/bin/bash
daemon:/usr/sbin:/usr/sbin/nologin
bin:/bin:/usr/sbin/nologin
sys:/dev:/usr/sbin/nologin
# many other lines
pit:/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

Manual reference: