I am trying to save the value of a command into a variable but it gives an error
var = `cat $1 | grep "STAN: \[$2\]" | awk -F '|' '{print $3; exit}'`
It gives me the error
var: command not found
I am trying to save the value of a command into a variable but it gives an error
var = `cat $1 | grep "STAN: \[$2\]" | awk -F '|' '{print $3; exit}'`
It gives me the error
var: command not found
Yes, that would give you an error, since the =
in variable assignments can't be surrounded by whitespace in the shell. The shell would interpret the line as you wanting to run the command called var
with the arguments =
and whatever your command substitution returns (after additionally splitting the result into words and applying file name globbing to those words, since it's unquoted).
Instead, use
var=$( awk -F '|' -v str="$2" '$0 ~ "STAN: \\[" str "\\]" { print $3; exit }' "$1" )
I also took the liberty to get rid of the grep
and the cat
, and to change the deprecated command substitution using backticks to one using $( ... )
instead.
You could also do it with grep
, cut
and head
:
var=$( grep -e "STAN: \[$2\]" "$1" | head -n 1 | cut -d '|' -f 3 )
or, if your grep
has the -m
option to stop after a particular number of matches:
var=$( grep -m 1 -e "STAN: \[$2\]" "$1" | cut -d '|' -f 3 )
or, if the expression that you're searching with is actually a string and not a regular expression:
var=$( grep -m 1 -F -e "STAN: [$2]" "$1" | cut -d '|' -f 3 )
var=foo
, notvar = foo
. Also is preferable to use$()
for command substitution instead of backticks:var=$(my command)
. – schrodingerscatcuriosity Mar 07 '21 at 10:00cat
:var=$(grep "STAN: \[$2\]" "$1" | awk -F '|' '{print $3; exit}')
– schrodingerscatcuriosity Mar 07 '21 at 10:04