Gil
Gil

Reputation: 1538

Passing the value of NR to a variable in AWK

Can we pass NR to a variable in awk ?

I have a script which goes like this :

     awk -v { blah blah..   
     ..........
     count--
     print count
    }
     if (count==0)
    {print "The end of function"
     print NR 
     exit
     } 

This is the awk part of the code . I want to pass the NR to var2 as :

    sed -n ''"$var1"','"$var2"'p'

Which has to be reused several times !

Thanks for your replies .

Upvotes: 3

Views: 2109

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 360163

As others have suggested, there are better ways to accomplish the overall goal.

However, in order to answer your specific question:

var2=$(awk 'END {print NR}' inputfile)

and add anything else you may need within the AWK script.

Upvotes: 3

Karl Nordström
Karl Nordström

Reputation: 327

If you only want to print a certain subset of lines you're almost there. The -v flag is the way to go.

awk -v var1=15 -v var2=25 'NR>=var1 && NR<=var2 {blah blah ...}'

Of course you have to change 15 and 25 to what you need. Observe that variables shoudn't be encapsulated in quotes.

Upvotes: 4

Birei
Birei

Reputation: 36272

I don't know what you want to achieve with awk, sed and the NR variable. Do you mean the number of lines of the file?

This command gets it:

wc -l infile | sed -e 's/ .*$//'

So, use it with -v switch to awk and use it as you want. Next command will print 10 because infile has ten lines in my computer.

awk -v num_lines=$(wc -l infile | sed -e 's/ .*$//') 'BEGIN { print num_lines }'

Upvotes: 3

Related Questions