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?
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.
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.
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.
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
awk '{print $'$myvar'}' < /tmp/in > /tmp/out
Where $myvar is your variable column (an integer). Watch out for script injections!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With