Cut Command
Understanding the Cut Command
The cut
command is a powerful utility in Unix-like
operating systems used for selecting columns of text from each line
of a file. It's particularly useful for extracting specific data
fields or characters from structured text files. If you require more
comprehensive pattern-directed scanning and processing, consider
using awk
.
Selecting Characters with Cut
You can use the -c
option to specify character
positions. For example, given a text file (file.txt
)
with the following content:
unix or linux os
is unix good os
is linux good os
Extracting a Single Character
To extract the fourth character from each line:
cut -c4 file.txt
Output:
x
u
l
Extracting Multiple Characters
To extract the fourth and sixth characters:
cut -c4,6 file.txt
Output:
xo
ui
ln
Extracting a Range of Characters
To extract characters from the fourth through the seventh:
cut -c4-7 file.txt
Output:
x or
unix
linu
Selecting Fields with Delimiters
The cut
command can also operate on fields (columns)
separated by a delimiter. Use the -d
option to specify
the delimiter and -f
to specify the field number.
Extracting the Second Field
To extract the second element, delimited by a space:
cut -d' ' -f2 file.txt
Output:
or
unix
linux
Extracting Multiple Fields
Similarly, you can extract multiple fields. To get the second and third fields:
cut -d' ' -f2,3 file.txt
Output:
or linux
unix good
linux good