AWK question

Hello everyone,

I have the following file:

# cat tmp
col1a col2a col3a
cola  col1a col2a
col3a col2b cola
col2a col3a col4a
colb  col2a colc

If I want to print lines where column 2 = col2a I can do something like:

# awk -v var=col2a ' var == $2 {print $0}' tmp
col1a col2a col3a
colb  col2a colc

Question: Any idea how I can print lines where column 2 = col2* ? (like the following desired output)

col1a col2a col3a
col3a col2b cola
colb  col2a colc
awk '$2 ~ /col2/ {print $0}' d.txt

I think a requirement is to pass the text to search for as a variable.

This should do it:

awk -v var='col2' '$2 ~ var'

Thanks for both answers they both work if I execute them in the command ligne however my goal is to pass the text to search for as a variable like pludi said.

In my script the following command isn't working: (where MY_VAR=col2a)

awk -F, -v var='${MY_VAR}' '$2 ~ /${var}/' tmp_file

Any idea?

Remove the quote.

Replace

/$var/

with

var

, like:

awk -v var=${MY_VAR} '$2 ~ var' tmp_file

It worked tongelja :wink:

Thanks everyone, cheers!

---------- Post updated at 05:14 PM ---------- Previous update was at 04:40 PM ----------

After checking my file I saw that sometimes I also have the string Col2 in the second column (which is different than col2)

Is there a way to use the previous AWK command (in a not case sensitive way)??

Thanks in advance

convert both sides of the 'match' to one case and compare [hint: tolower(str)]

Try to use the toupper() function

awk -v var=${MY_VAR} 'toupper($2) ~ toupper(var)' tmp_file
${MY_VAR}

should be double quoted as it may contain shell meta chars.

awk -v var='col2' '$2 ~ var'

may have false positive as it matches:

col1a notcol2a col3a

It should be

awk -v var='^col2' '$2 ~ var'

if you want to only match lines with field 2 starting with col2.