LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   How can I pass variable to "awk" ? (https://www.linuxquestions.org/questions/linux-software-2/how-can-i-pass-variable-to-awk-894414/)

915086731 07-29-2011 12:59 AM

How can I pass variable to "awk" ?
 
Please see the following code, I can not pass the var "a" to awk.It seems that $a is not identified. How to resolve it ?
Thanks

Code:

[river@localhost sda5]$ a=2
[river@localhost sda5]$ awk 'NR==$a' t.txt
[river@localhost sda5]$ awk 'NR==2' t.txt
All rights reserved. Use is subject to license terms.


grail 07-29-2011 01:02 AM

Check out '-v' option

catkin 07-29-2011 01:02 AM

Change from single quotes to double quotes, from awk 'NR==$a' t.txt to awk "NR==$a" t.txt

915086731 07-29-2011 01:04 AM

Thanks , but why? What is the difference between single quotes and double quotes.

catkin 07-29-2011 01:09 AM

Quote:

Originally Posted by 915086731 (Post 4428217)
Thanks , but why? What is the difference between single quotes and double quotes.

Strings within single quotes are not changed by bash. Inside double quotes, bash substitutes variable values as you want (and does other things). This is explained in all bash tutorials, the bash man page and here (which is the man page plus, online).

915086731 07-29-2011 01:12 AM

Thanks .

915086731 08-11-2011 07:33 AM

But problem comes with following command:
Code:

[river@localhost Desktop]$ awk  "NR==$a {print $2}" t.txt
All rights reserved. Use is subject to license terms.

Why does it print all fields? How to resolve it.
Thanks!!


All times are GMT -5. The time now is 03:10 PM.