Using cut command in Linux


“cut” command is a good method for parsing and extracting certain strings from texts especially within bash scripts. Below are some examples on how to extract certain information from different texts.

For example, obtaining the IP address from ifconfig by using a combination of grep and cut:

ifconfig eth1 | grep “inet addr” | cut -d : -f 2

Linux cut command

Linux cut command

 

By default, this command will use the tab space as separator between words, but this can be changed with the -d character option.

The -f option is used to specify what fields from the selected text will be extracted.

We can further extract just the IP address from this output by using the awk command, as follows:

ifconfig eth1 | grep “inet addr” | cut -d : -f 2 | awk ‘{print $1}’

The above command will print the first field of the text which in this case is the IP address.

 

If we want to extract the MAC address from our network interface, we would simply use the following command:

ifconfig eth1 | grep -i “hwaddr” | cut -d ” ” -f 11

Note that the separator in this case is a space ” ” but there are sections which contain multiple space characters:

get Mac address in Linux

get Mac address in Linux

 

 

 

Of course, we can obtain the Mac address by using the arp command with -a or -n options:

Linux MAC address

Linux MAC address

Let’s take another example and extract the usernames from the passwd file:

cut -d “:” -f 1 /etc/passwd

You can specify multiple fields to be extracted with the -f option, just like in the following example:

cut -d “:” -f 1,7 /etc/passwd

The command will display the usernames and also their default shell.

We can exclude fields from being displayed by running the following command:

cut -d “:” –complement -s -f7 /etc/passwd

With cut command you can extract and manipulate data from within files in many ways. You can select different bytes, columns or characters from within texts. I’ll let you inspect the man file for this command to view all options available.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s