3

How to print nth column in a file using awk?To print the second column of file, I try:

#!/bin/bash   
awk '{print $2}' file

But if n is a variable, how to print nth column of file using awk?

#!/bin/bash   
n=2
user7328234
  • 393
  • 7
  • 23
  • hi, `awk '{n=2; print $n}` file – NishanthSpShetty Oct 30 '17 at 09:09
  • This is a dupe, you can see lots of similar questions on this topic of using shell variables in `Awk`. The title could suggest awk script, but it is all the same, using shell variables in a script (or) command – Inian Oct 30 '17 at 09:12

2 Answers2

4
n=2
awk -v var="$n" '{print $var}' file
tso
  • 4,732
  • 2
  • 22
  • 32
2

Give a try this, notice the -v option:

#!/bin/bash

n=3

awk -v x=${n} '{print $x}' file

From the man page:

The option -v followed by var=value is an assignment to be done before 
prog is executed; any number of -v options may be present.

For more examples, you could check Using Shell Variables in Programs

nbari
  • 25,603
  • 10
  • 76
  • 131