Cut Command Unix
Cut Command Unix
Let's revisit some important things about cut command in *NIX operating system. It's
one of your helpful mates when awk command is not available.
1) The cut command is used to display selected part of file content in UNIX.
2) The default delimiter in cut command is "tab", you can change delimiter with the
option "-d" in the cut command.
3) The cut command in Linux allows you to select part of content by bytes, by
character, and by field or column.
4) The cut command in UNIX or Linux can work with files or you can pipe it with the
output of other UNIX/Linux command.
s
As seen above, the characters a, p, s are the second character from each line of the
test.txt file.
cat
cp
ls
The following specifies only the start position before the ‘-‘. This example extracts from
3rd character to end of each line from test.txt file.
The following specifies only the end position after the ‘-‘. This example extracts 8
characters from the beginning of each line from test.txt file.
cat comm
cp comma
ls comma
The entire line would get printed when you don’t specify a number before or after the ‘-‘
as shown below.
The following example displays only first field of each lines from /etc/passwd file using
the field delimiter : (colon). In this case, the 1st field is the username. The file
root
daemon
bin
sys
sync
games
bala
root:/root
bala:/home/bala
To display the range of fields specify start field and end field as shown below. In this
example, we are selecting field 1 through 4, 6 and 7
root:x:0:0:/root:/bin/bash
bala:x:1000:1000:/home/bala:/bin/bash
In the following example, we’ve specified the delimiter as | (pipe), and cut command
simply displays the whole line, even when it doesn’t find any line that has | (pipe) as
delimiter.
root:x:0:0:root:/root:/bin/bash
bala:x:1000:1000:bala,,,:/home/bala:/bin/bash
But, it is possible to filter and display only the lines that contains the specified delimiter
using -s option.
The following example doesn’t display any output, as the cut command didn’t find any
lines that has | (pipe) as delimiter in the /etc/passwd file.
The following example displays all the fields from /etc/passwd file except field 7
root:x:0:0:root:/root
bala:x:1000:1000:bala,,,:/home/bala
To change the output delimiter use the option –output-delimiter as shown below. In this
example, the input delimiter is : (colon), but the output delimiter is # (hash).
root#/root#/bin/bash
bala#/home/bala#/bin/bash
bala
/home/bala
/bin/bash
Once you master the basic usage of cut command that we’ve explained above, you can
wisely use cut command to solve lot of your text manipulation requirements.
The following example indicates how you can extract only useful information from
the ps command output. We also showed how we’ve filtered the output of ps command
using grep and sed before the final output was given to cut command. Here, we’ve used
cut option -d and -f which we’ve explained in the above examples.