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.
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
To extract the fourth character from each line:
cut -c4 file.txt
Output:
x
u
l
To extract the fourth and sixth characters:
cut -c4,6 file.txt
Output:
xo
ui
ln
To extract characters from the fourth through the seventh:
cut -c4-7 file.txt
Output:
x or
unix
linu
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.
To extract the second element, delimited by a space:
cut -d' ' -f2 file.txt
Output:
or
unix
linux
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