Pass column number as variable to awk and compare with a string.

Hi All,

I have a file test.txt.

Content of test.txt :

1 vinay se
2 kumar sse
4 kishore tl

I am extracting the content of file with below command.

awk '$2 ~ "vinay" {print $0}' test.txt

Now instead of hardcoding $2 is there any way pass $2 as variable and compare with a pattern ?

In short i would like to know whether is there a way to configure the column name in awk?

Kindly let me know if i am not clear

Yes. Try

deleted due to major inaccuracy

or

deleted due to major inaccuracy

Yes it works.

Can you please help me if i want to execute the same on remote server?

That depends on what you mean when saying "$2".
If you want the second positional parameter of the function or shell script to be used, junior-helper's 2. proposal is fine, assumed that parameter holds an integer number.
If you want the file's second column to be addressed, use a plain 2 in j-h's script:

awk -v COL=2 '$COL ~ "vinay" {print $0}' test.txt

@junior-helper: I don't think your first proposal will work, as it tries to match $$2 against "vinay" ...

---------- Post updated at 11:12 ---------- Previous update was at 11:06 ----------

Some more context, please.

@RudiC

I would like execute a command as below.

ssh user@host " AWK Command "

But the AWK command should be flexible enough to compare the pattern with column which is passed as input.

For example :

For below o/p i want to check for pattern 9511 in only 2nd column or only 1st column.
I need to pass the column as i/p variable to awk and compare with the pattern.

$ netstat -an | grep 951
200.103.10.10.50224 100.103.10.10.9511 49640 0 49640 0 ESTABLISHED
200.103.10.10.50263 100.103.10.10.9512 49640 0 49640 0 ESTABLISHED
200.103.10.10.50278 100.103.10.10.9513 49640 0 49640 0 ESTABLISHED
200.103.10.10.50292 100.103.10.10.9514 49640 0 49640 0 ESTABLISHED

RudiC,
I don't know why, but it works (I always test the commands before posting them).
I also think there is (almost) no difference between my 2 proposals.
If the first would fail, the second would fail too, no(?)

It seems to work because $COL will evaluate to $0 when COL has a string value. So your code will match $0 against "vinay" and print the entire first line. Test this by setting col='$3' or adding some fields to the file.
The same is valid for your second proposal - if no positional parameter is available, you'll match $0 against "vinay". Test this by e.g. set -- 2 3 4 and running your code. $2 will be "3", and field 3 doesn't have "vinay" - nothing's printed...

---------- Post updated at 12:12 ---------- Previous update was at 12:10 ----------

What's the results of using the proposals in this thread for your " AWK Command "?

1 Like

Girish19,
important! You'll want to use:

RudiC,
spot-on! I have got it!
Both proposals failed when I added a fourth record with "vinay" in the third field :rolleyes: