[SOLVED] BASH - unable to replace variable in script
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
cat /mydir/test.log | awk ' BEGIN {tmp =1} { if ($0 ~ /191:$MYVARIABLE/ && $0 ~ /Request URL is/) { (tmp=tmp+1) }} END {print tmp}'
I tried declaring a variable "MYVARIABLE", and then tried using it in the next statement.. The problem is, when a statement is enclosed in SINGLE QUOTES, variable substitution doesn't occur. I tried using '\047' for single quotes, and that didn't help either.. How do I get around this problem.
When using double quotes, bash will change the $0 strings to whatever the value of $0 is. This can be avoided by "backslash escaping" the $0s, changing them to \$0
As you realized, single quotes prevent shell variable expansion. If you replace them with double quotes, it will expand, but then the shell will also attempt to interpret other values as well, particularly the "$0". You can use creative quoting and escaping so that only the value you want is expanded, but that gets tricky, tiresome, and hard to read.
The better option is to import the shell variable value into an awk variable. This is usually done with the -v option.
Finally, environment variables are generally all upper-case. So while not absolutely necessary, it's good practice to keep your own user variables in lower-case or mixed-case, to help differentiate them.
Last edited by David the H.; 01-22-2012 at 04:53 AM.
Reason: some rewording
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.