3

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
Hamza Azam
  • 31
  • 3

1 Answers1

8

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 )
Kusalananda
  • 333,661
  • Another big benefit of the first, awk-based, solution in this answer is that the exit status of the $(...) is a better indication of whether or not everything worked. – James Youngman Mar 07 '21 at 21:17