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?

0

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

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 $0 means the entire current line.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.