cut

cut

As its name implies, this handy utility is used to cut and display selected information from a text file.  Think of it as something that will take a vertical slice of a text file, and send it to the output of your choice.  There are two ways to specify where you want to begin and end the slice.  You can specify it either by a starting and an ending character, or by fields.



Slice By Fields
To specify your "slice" by fields, you'll need to use both the -d and -f switches.  The -d switch will specify the delimiter,  the character that separates the fields.  That's so that cut will know where each field begins and ends.   The -f switch will specify which fields you want to look at.  In this diagram, you see that cut was used  to extract the user name and directory fields, 1 and 6 from the /etc/passwd file.  Since the fields in this file are separated by colons, you need to indicate that with  "-d:" for the delimiter switch.

cut command


Selecting By Character
The other method for specifying the "slice" is the character method.  That's actually a misnomer; it should be called the column method, since you are selecting the columns that you want to display.  If you wanted to record the IP Address and date/time of customers who come to your website you can cut the first 45 columns out of your access_log to capture that information.

cut -c1-45 access_log
66.249.68.27 - - [18/Jul/2009:15:19:49 -0600]


Of course, with both of the above examples, you have the option of using a stdout redirector to save the extracted information to a text file.   For example--

cut -d: -f 1,6 /etc/passwd > passwd_file

or

cut -c1-45 access_log  > logfile

As with most of the text-stream filter utilities, you can either pipe the output from cut into another utility, or pipe another utility's output into cut.  

cat access_log | cut -c1-45
174.129.166.91 - - [13/Jul/2009:05:23:56 -060
80.219.208.245 - - [13/Jul/2009:05:24:11 -060
174.129.166.91 - - [13/Jul/2009:05:24:11 -060
72.30.142.105 - - [13/Jul/2009:05:24:20 -0600
174.129.166.91 - - [13/Jul/2009:05:24:22 -060
174.129.166.91 - - [13/Jul/2009:05:24:33 -060
94.141.128.10 - - [13/Jul/2009:05:24:33 -0600


sh exit.sh jane
USERNAME: jane
NAME: /home/jane
HOMEDIR: /home/jane
z4@m67:~/scripts$ sh exit.sh joe
Cannot find user joe in /etc/passwd

 


Copyright CyberMontana Inc. and BeginLinux.com
All rights reserved. Cannot be reproduced without written permission. Box 1262 Trout Creek, MT 59874