Using AWK to get a specific line using a variable

Hi

I have a text like this
example.input

1 red
2 blue
3 green

If I set this

c=2

Then try

awk 'NR==$c { print $2 }' example.input

I do get nothing

If I try

awk 'NR==2 { print $2 }' example.input

i get

blue

I know this can e down with head/tail/sed, but I like it to work in AWK

What is wrong?

awk -v c=2 'NR==c { print $2 }' example.input

Shell and awk variables are different.

c=2
awk -v VM="$c" 'NR == VM{print $2}' file

found solution my self using google some more :slight_smile:

awk 'NR=='$c' { print $2 }' example.input

adding singe quote

Thanks for your quick responce

That solution is worse than the ones other people posted. There's two proper ways to get a variable into awk, and that's not either of them :wink:

export c=2
awk 'NR == ENVIRON["c"] { print $2 }' example.input

Why is it worse?
Is it more slow?
May not work with all variable?

For me it works, and its minimum of programing

It's less safe. Not all variables will work in it, especially strings, and if anything even slightly resembling awk syntax is in there, awk will throw syntax errors.

After all, you're changing the program code that way, not the value of a variable. And anything can happen when you put the right (or wrong) things into a program.

$ c="1 ; print 'Hello World'"
$ awk 'NR=='$c' { print $2 }' filename

awk: cmd. line:1: fatal: cannot open file `;' for reading (No such file or directory)

$

You might like the old-fashioned way of doing it, it's pretty short and straightforward:

awk 'NR==C { print $2 }' C="$c" filename

You can put any string you want in there, including strings, and even strings with spaces in them, without causing awk syntax errors.

Thanks allot, I am still learning.
Will update my code :slight_smile: