Hey guys. Im trying to create a script that Create a one-line script named awkscript.sh that uses awk to read its standard input and extract the column of input given as an argument on the command line.
What do i put in vi?
For example: (the script name is awkscript.sh)
$ echo a b c d e f | ./awkscript.sh 1
a
$ echo a b c d e f | ./awkscript.sh 2
b
$ echo a b c d e f | ./awkscript.sh NF
f
Put this code in file: awkscript.sh
p="$1"
awk -v P="$p" '
{
for (i=1; i<=NF; i++)
{
if (i == P)
print $i
if (P == "NF" && i == NF)
print $i
}
} '
Or..
Put this in your script..
awk -v var="$1" '{ print var!="NF"?$var:$NF}'
works perfectly
thank you. Im a noobie to learning awk. Can you explain to me that full command?
awk -v var="$1" '{ print var!="NF"?$var:$NF}'
Have you tried mine solution..?
$ cat test.sh
awk -v var="$1" '{ print var!="NF"?$var:$NF}'
$ echo a b c d e f | ./test.sh NF
f
$ echo a b c d e f | ./test.sh 4
d
yes it worked. I mistyped it. sorry
It's ok..
awk -v var="$1" # It uses var for saving $1(number which are passed to the script is $1).
'{ print var!="NF"?$var:$NF}' # Here we check if variable var is not equal to "NF". If it is a number/not equal to "NF" then directly print $var(print that column value).
If it is "NF" then print $NF.
Hope this helps you
Pamu
Thanks so much! this helped a lot! I understand until the point ?$var:$NF. I dont understand that part.
This can be written as..
Condition?True:False
Here we are using var!=NF as condition.
If condition satisfies then execute true part. If condition fails then execute false part.
As var is not equal to "NF" then print $var
And if var is equal to "NF" then print $NF
Again, thank you! Explained very well ![]()