0

I want to call awk from a bash script like this:

#!/bin/bash
awk -vFPAT='[^ ]*|"[^"]*"|\\[[^]]*\\]' '{ print $2 }' $1

I want $2 to be a number that I specify. So if the script is named get-log-column I'd like to be able to call it this way: get-log-column /var/log/apache2/access.log 4

In this example, 4 would be the column so the output would be column 4 from access.log.

In other words, if access.log looked like this:

alpha beta orange apple snickers 
paris john michael peace world

So the output would be:

apple
peace
  • Seems your `"` and `'` characters were not correctly pasted in your post, so edited them now, request you to be careful while pasting contents into the posts. – RavinderSingh13 Oct 25 '19 at 05:05
  • 1
    Possible duplicate of [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script) – tripleee Oct 25 '19 at 06:01
  • @tripleee, Hi sir, IMHO, I know it is duplicate of how to pass a shell variable into awk, since OP's question has to club it with printing as a specific column with value of variable that is the reason I haven't closed it as a dup. If I missed something then kindly do let me know I will make it dup ASAP then. – RavinderSingh13 Oct 25 '19 at 06:08

2 Answers2

0

Could you please try following.

#!/bin/bash
var="$1"
awk -v FPAT='[^ ]*|"[^"]*"|\\[[^]]*\\]' -v varcol="$var" '{ print $varcol }' Input_file

Explanation:

Have created a shell variable var which will have $1 value in it. Where $1 value is the argument passed to script. Now in awk we can't pass shell variables directly so created 1 awk variable named var_col which will have value of var in it. Now mentioning $varcol will print column value from current line as per OP's question. $ means field number and varcol is a variable which has user entered value in it.

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

This may work

#!/bin/bash
awk -v var="$1" -v FPAT='[^ ]*|"[^"]*"|\\[[^]]*\\]' '{ print $var }' $1

See this on how to use variable from shell in awk How do I use shell variables in an awk script?

Jotne
  • 40,548
  • 12
  • 51
  • 55