Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a particular column using awk or cut or perl

Tags:

I have a requirement to select the 7th column from a tab delimited file. eg:

cat filename | awk '{print $7}' 

The issue is that the data in the 4th column has multiple values with blank in between. example - The last line in the below output:

user  \Adminis FL_vol Design         0         -       1       - group        0 FL_vol Design   19324481         -    3014       - user      \MAK FL_vol Design   16875161         -    2618       - tree       826 FL_vol Out Global Doc Mark     16875162         -    9618       - /vol/FL_vol/Out Global Doc Mark 
like image 252
javed Avatar asked Dec 10 '12 04:12

javed


People also ask

Can I use cut with awk?

You can cut in awk using awk's function split . You can also filter records using a regex condition within awk, making grep and cut superfluous. This breaks down like: Set the output field separator to be a pipe between two spaces.

Can we use awk in Perl?

in Perl. If you have an existing awk program, and wish it to run with Perl, you can perform a mechanical translation using the a2p utility provided with the Perl distribution. This utility converts the awk syntax into the Perl syntax, and for the vast majority of awk programs, provides a directly runnable Perl script.

Is awk faster than cut?

awk is more powerfull than cut. if you need to use tail or head or sort or similars, and cut, you can make one single awk for that. Like other posters said, if you can use cut for you problem you should choose it instead of awk, but there are situations where cut just isn't enough.


2 Answers

If the data is unambiguously tab-separated, then cut will cut on tabs, not spaces:

cut -f7 filename 

You can certainly do that with awk, too:

awk -F'\t' '{ print $7 }' 
like image 101
tripleee Avatar answered Sep 18 '22 15:09

tripleee


If fields are separated by tabs and your concern is that some fields contain spaces, there is no problem here, just:

cut -f 7 

(cut defaults to tab delimited fields.)

like image 41
ysth Avatar answered Sep 18 '22 15:09

ysth