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
1 Answer 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.
awk -v v="$var"
"$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?"