Tuesday, August 28, 2007

string manipulation using cut linux command

Another way to parse and manipulate string characters is by using linux command cut.

Man page says
Cut removes sections from each line of files. Cut writes to standard output selected parts of each line of each input file, or standard input if no files are given or for a file name. An exit status of zero indicates success, and a nonzero value indicates failure.

Here are several examples of using cut linux command.

Sample 1:
Returns the first set of word marking space ' ' as a columnar separator
# who am i

returns
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
root pts/2 2007-08-27 06:23 (:0.0)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Using cut for getting the first word 'root' would be

# who am i | cut -f1 -d' '


Sample 2:

Linux /etc/passwd password file is consists of many fields like username, groupid, name, and more. The fields are normally separated by a field : (colon) . To retrieve or list down all usernames from /etc/passwd password file would be like

# cut -d: -f1 /etc/passwd


Sample 3:

By specifying space ' ' as the delimited character or field marker to separate set of words, the below sample then instructs to cut the remaining words separated by space character and to retain only words from 1st, 2nd, 7th and 8th columnar position like so

# echo "I like bayabas, I always watch sesame street." | cut -d' ' -f1,2,7,8

would have a output return of
~~~~~~~~~~~~~~~~~~~~~~~~~
I like sesame street.
~~~~~~~~~~~~~~~~~~~~~~~~~

Sample 4.
Cut can trim down phrases too by specifying the Nth positional character which needs to be retained like so

# echo "I know Linux is good." | cut -c 8-

would have a return of
~~~~~~~~~~~~~~~~~~~~~~~
Linux is good.
~~~~~~~~~~~~~~~~~~~~~~~

Sample 5.
Another string parsing example using cut is by specifying a starting point from Nth position with an ending Nth positional character point. This would be like like FROM to TO like so

# echo "I know Linux is good." | cut -c 8-12

would also have a return of
~~~~~~~~~
Linux
~~~~~~~~~

Lastly, reversing the specification of FROM and TO would be and retaining the rest of the words like so

# echo "I know Linux is good." | cut -d' ' -f3,4 --complement

We removed the 3rd and 4th field from words separated by space ' ' character. This would return
~~~~~~~~~~~~~~~
I know good.
~~~~~~~~~~~~~~~

Cheers

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy