Thursday, April 23, 2009

Retrieve column from file using cut utility in linux

Suppose we have following file named student_info.txt where first field is student ID, second field is grade and third field is department.

# vi student_info.txt
024401 4.98 CIT
022401 3.98 EEE
021401 4.76 MCE
024402 4.02 CIT
022402 3.99 EEE

Note that fields are separated by tab delimiter.

With the cut utility we can extract first or second or third field from the file.
The syntax of usage cut command is,
cut -f{field number} {file-name}

Where the field number is the column number in the file, like 1,2,3 etc. Note that field number is adjacent with -f, so there is no whitespace between them.

And the file-name is the name of the file.

Now we want to extract the list of student ID i.e first field in the field. Then use it as,

# cut -f1 student_info.txt
024401
022401
021401
024402
022402

We can also save the output to a file. Suppose we want to extract the grade information from the file and save it inside grade.txt file. Use it as,

# cut -f2 student_info.txt >grade.txt

# cat grade.txt
4.98
3.98
4.76
4.02
3.99

To extract student ID information into file id.txt issue,
# cut -f1 student_info.txt >id.txt

# cat id.txt
024401
022401
021401
024402
022402

Related Documents
http://arjudba.blogspot.com/2009/04/getopts-command-in-linux-shell-script.html

No comments:

Post a Comment