-1

I've tried to assign the output of an Awk command to a variable but I receive an error. I would like to assign and the echo the result in the variable.

count = `awk '$0 ~ /Reason code "68"/' ladb.log | wc -l`

I've enclosed the statement in backticks and receive this error below

/lsf9/db/dict/=: Unable to open dictionary: No such file or directory
DataArea =              does not exist
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Configueroa
  • 315
  • 4
  • 14
  • 2
    Does your script have spaces around the `=`? – kdhp Mar 01 '17 at 23:26
  • 1
    If your script has spaces around the `=` as shown, then you're executing a command `count` with `=` as the first argument and the output of the `awk … | wc -l` as the other argument. And, for whatever reason, the `count` command doesn't like the `=` as the name of a dictionary, so it complains. Shell scripting is intensely space sensitive, and spaces are not allowed around the assignment operator in assignments (or, more accurately, your intention will be completely misinterpreted if you put spaces around what you think is an assignment operator). – Jonathan Leffler Mar 02 '17 at 00:11
  • 1
    Possible duplicate of [How to set a variable to the output from a command in Bash?](http://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash) – Benjamin W. Mar 02 '17 at 01:03
  • 1
    Also try `count=$(grep -c 'Reason code "68"' labd.log)`. – Walter A Mar 02 '17 at 23:23

1 Answers1

0

Your main problem is your usage of spaces. You can't have a spaced assignment in shell scripts.

Backticks may be harmful to your code, but I haven't used IBM AIX in a very long time, so it may be essential to your Posix shell (though this guide and its coverage of $(…) vs `…` probably don't suggest a problem here). One thing you can try is running the code in ksh or bash instead.

The following code assumes a standards-compliant Posix shell. If they don't work, try replacing the "$(…)" notation with "`…`" notation. With these, since it's just a number being returned, you technically don't need the surrounding double quotes, but it's good practice.

count="$(awk '$0 ~ /Reason code "68"/' ladb.log | wc -l)"

The above should work, but it could be written more cleanly as

count="$(awk '/Reason code "68"/ {L++} END { print L }' ladb.log)"

As noted in the comments to the question, grep -c may be faster than awk, but if you know the location of that text, awk can be faster still. Let's say it begins a line:

count="$(awk '$1$2$3 == "Reasoncode\"68\"" {L++} END { print L }' ladb.log)"

Yes, Posix shell is capable of understanding double-quotes inside a "$(…)" are not related to the outer double-quotes, so only the inner double-quotes within that awk string need to be escaped.

Adam Katz
  • 14,455
  • 5
  • 68
  • 83