Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the Nth column of a text file with AWK using argv

Tags:

unix

awk

Suppose I have a text file with data separated by whitespace into columns. I want to write a shell script which takes as input a filename and a number N and prints out only that column. With awk I can do the following:

awk < /tmp/in '{print $2}' > /tmp/out 

This code prints out the second column.

But how would one wrap that in a shell script so that a arbitrary column could be passed in argv?

like image 991
speciousfool Avatar asked Nov 26 '08 06:11

speciousfool


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

What is awk '{ print $3 }'?

txt. If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What does awk '{ print NF }' do?

The “NF” AWK variable is used to print the number of fields in all the lines of any provided file. This built-in variable iterates through all the lines of the file one by one and prints the number of fields separately for each line.


2 Answers

awk -v x=2 '{print $x}'

or in a shell script:

 #!/bin/sh num=$1 awk < /tmp/in -v x=$num '{print $x}' > /tmp/out 
like image 63
Ray Avatar answered Oct 16 '22 09:10

Ray


awk '{print $'$myvar'}' < /tmp/in > /tmp/out 

Where $myvar is your variable column (an integer). Watch out for script injections!

like image 26
strager Avatar answered Oct 16 '22 10:10

strager