Using shell variables in awk

It is possible to use shell variables within a awk command in a shell script.
As mentioned in the GNU Awk official documentation, one use case is that the shell variable holds the pattern that will be used by awk.
Here is one of the given examples :


printf "Enter search pattern: "
read pattern
awk -v pat="$pattern" '$0 ~ pat { nmatches++ }
END { print nmatches, "found" }' /path/to/data

If the pattern search is a bit more complicated than the one below $0 ~ pat, then this feature does not work anymore.

More details :

AWK : Using Shell Variables in Programs

Advertisements

[:ne binary operator expected

[:ne binary operator expected

In addition to the explanation here, this error pops up when comparing two values.
Pay attention either comparing is about comparing two strings or two numeric values.

As a reminder :

Numeric comparisons


val1 -eq val2
val1 -ne val2
val1 -ge val2
val1 -gt val2
val1 -le val2
val1 -lt val2

Strings comparisons


val1 = val2
val1 != val2
val1 val2
-n val1
-z val2

Further readings :

https://www.linuxtechi.com/compare-numbers-strings-files-in-bash-script/