34

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?

Good Person
  • 1,437
  • 2
  • 23
  • 42
speciousfool
  • 2,620
  • 5
  • 28
  • 33

2 Answers2

45
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
Ray
  • 2,238
  • 1
  • 20
  • 21
7
awk '{print $'$myvar'}' < /tmp/in > /tmp/out

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

strager
  • 88,763
  • 26
  • 134
  • 176