0

I have a comma-separated .txt file structured like this:

ABC,NAME1,LASTNAME1
DEF,NAME2,LASTNAME2
GHI,NAME3,LASTNAME3

When running:

$ ./script.sh file.txt

#!/bin/bash
awk -F, '/NAME1/{print $3}' "$1"

I get my desired output:

LASTNAME1

When trying to replace NAME1 by passing a variable to awk:

$ ./script.sh file.txt NAME1

#!/bin/bash
awk -v n="$2" -F, '/$n/{print $3'} "$1"

I do not get any output at all. I checked, that $2 entered in bash really is NAME1. What am I missing?

Joaquin
  • 2,013
  • 3
  • 14
  • 26
Shushiro
  • 577
  • 1
  • 9
  • 32

1 Answers1

2

Variable names in Awk are not prefixed with a $, so it should be just n instead of $n. Also, you cannot use variables inside a /.../ expression. You can write like this:

awk -v n="$2" -F, '$0 ~ n {print $3}' "$1"

Btw, if the n parameter should match the value in the 2nd column exactly, then it's better to use an exact matching condition with == on $2:

awk -v n="$2" -F, '$2 == n {print $3}' "$1"
janos
  • 120,954
  • 29
  • 226
  • 236
  • ah, I see! So, this awk command means: search in column 1 ($0) and if pattern (n) matches (~), print..." ? during my research, I also found, that $0 means line one? which is correct – Shushiro Oct 28 '17 at 09:55
  • @Shushiro `$0` means the entire current line. – janos Oct 28 '17 at 09:57