Reputation: 1619
I have made an awk implementation of grep -c ^str file
and I want to pass the file
and str
arguments from a shell script. I am using awk -v
twice to pass the arguments but I get a awk: cannot open var1 (No such file or directory)
error.
I just can't get around it, I've been trying for almost an hour.
My code:
read -p "Give me a file name " file
read -p "Give me a string " str
awk -v var1="$file" -v var2="$str" 'BEGIN{print var1; print var2}{/^var2/}' var1 |
awk '{if ($0 != "/s") {count++}} END {print count}'
Upvotes: 1
Views: 98
Reputation: 14955
It should be:
awk -v var1="$file" -v var2="$str" 'BEGIN{print var1; print var2}{/^var2/}' $file
awk
vars can only be acceded inside awk
code (delimited by single quotes in this case) not at shell level where var1
means nothing.
Note that var2
value will be just a literal string between slashes /^var2/
, use $0 ~ "^"var
instead to access var2
value.
In fact, your awk
code can be rewritten as:
awk -v var="$str" '$0 ~ "^"var && $0 != "/s"{count++}END{print count}' $file
Upvotes: 2