Reputation: 1743
Below is the sample shell script, Here the value of NF is coming Null instead of 9 (the output of expression on line 4)
#!/bin/bash
#set -x
VAR="The quick brown fox jumped over the lazy dog."
NF=`echo $VAR | awk '{PRINT NF}'`
echo "$NF"
Any thoughts?
Upvotes: 1
Views: 81
Reputation: 41456
Here is one way to do it (using Here String). PS always double quote variable like this "$var"
NF=$(awk '{print NF}' <<< "$var")
Upvotes: 1
Reputation: 74635
Others have explained what was wrong with your code. I would like to suggest another way to count the number of words:
var="The quick brown fox jumped over the lazy dog."
wc -w <<<"$var"
Or on older shells:
echo "$var" | wc -w
Upvotes: 1
Reputation: 4516
The command you're looking for is print
, not PRINT
. Awk is case-sensitive.
Also, it is recommended to use the following command substitution: $(...)
instead of backticks (`
).
So in your case:
NF=$(echo $VAR | awk '{print NF}')
Upvotes: 2
Reputation: 7582
AWK is case-sensitive. You want the function print
.
By writing PRINT NF
instead, AWK interprets that as the names of two variables, concatenated. PRINT
has an empty value; NF
has the value "9". You didn't ask it to do anything with the result (such as printing it), so the AWK script produces no output for that line of input.
Upvotes: 3