1

This question already has an answer here:

I am trying to pass a variable that contains spaces from bash to awk. I have simple a simple script for doing this with single string variables (in which I am searching the first column of the FILE for the variable), for example:

var=string

awk -v v=$var '(index($1, v) !=0) {print}' FILE

This does not work if var="string1 string2". I have new searches where the variables are groups of words separated by spaces as in second var. E.g.,

var="string1 string2 string_n"

awk -v v=$var '(index($1, v) !=0) {print}' FILE

marked as duplicate by G-Man, Stephen Rauch, αғsнιη, Shadur, GAD3R Nov 10 '17 at 10:15

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 4
    Isn't it just a matter of quoting the shell expansion? i.e. awk -v v="$var" – steeldriver Nov 10 '17 at 1:12
  • 1
    @G-Man It is not a security question, it is a scripting question. I find the initiative to close it as a dupe of a security question surreal. The relevant security implications could be mentioned as related matter, but an answer to this question would be essentially different as the dupe candidate. – peterh Nov 10 '17 at 6:08
  • 1
    @G-Man Yes. I've seen a 5 page long security-tuned scripting documentation, which includes the required roughly 3-line answer to this question. – peterh Nov 10 '17 at 6:14
  • 1
    Stack Exchange believes in having “canonical” questions. That is the Unix & Linux Stack Exchange definitive canonical reference question on the pitfalls of failing to quote a variable in bash/POSIX shells. Why the author chose to title it that way, I don’t understand; but you have judged a book by its cover — it (Stéphane Chazelas’s question) is not a security question; it is a scripting question.  … (Cont’d) – G-Man Nov 10 '17 at 6:30
  • 1
    (Cont’d) …  Yes, the answer is “You should always quote your shell variable references (e.g., "$var") unless you have a good reason not to, and you’re sure you know what you’re doing.” — but that’s the answer to a thousand questions, and there’s very little benefit to having the same answer duplicated on the site a thousand times — especially if it leads 1000 OPs to ask “Why?” – G-Man Nov 10 '17 at 6:30
-1

You have to put $var into double apostrophes also in the awk command, so:

varName="a string with spaces"
awk -v var="$var" '{...your awk code...}'

It is because your awk command will be called by a shell, and most shells, including bash, forget the tokens after variable substitution.

Not the answer you're looking for? Browse other questions tagged or ask your own question.