Understanding A Particular Line of Nawk Command

408 views Asked by At

I am going through shell scripting online lessons as my work requires me to learn shell scripting.

I came across "awk" and "nawk " commands and my learning hasn't yet reached up to it.

In a nutshell, I know that awk/nawk search for a particular pattern and perform an action in case a match has been found.

Even despite of that, I couldn't understand what the following line is meant for:

eval $( cat ${MMORPHYDIR}/${PWFILE} | nawk ' /^#BEGIN '${ENV_NAME}'/,/^#END '${ENV_NAME}'/ { print }' | egrep "${USEFULL_PARAM}" )

Please help me to understand what this line does or is intended to do.

2

There are 2 answers

2
karakfa On
... awk '/start/,/end/'

prints the records between start and end patterns. {print} can be omitted since it's implied. The ^ in your script indicates beginning of a line.

Note that cat and eval are unnecessary, the same can be written as

$ awk '...' "${MMORPHYDIR}/${PWFILE}"

also grep can be included in the awk script as well.

0
Ed Morton On

awk is THE standard, general purpose tool for manipulating text on all UNIX-like systems. There are various flavors of awk, all with the same core functionality plus some differences. nawk is the very unfortunately named new awk because it was named that about 30 years ago as the successor to 1977s old awk (e.g. /bin/awk on Solaris, aka old, broken awk which must never be used) and is now actually best avoided as it doesn't even support the minimal awk functionality required by POSIX (e.g. character classes). Important lesson there: never use the word "new" in the name of any software entity!

The best awk to use these days is GNU awk, gawk, as it supports all POSIX functionality plus a ton of useful extensions, is generally available, is extremely well documented, and has a massive user base.

wrt:

eval $( cat ${MMORPHYDIR}/${PWFILE} | nawk ' /^#BEGIN '${ENV_NAME}'/,/^#END '${ENV_NAME}'/ { print }' | egrep "${USEFULL_PARAM}" )

That is a complete mess, doing literally about a dozen things that should never be done in shell or in awk. Trying to explain it would be like trying to explain someone mixing concrete with a screwdriver. Forget you ever saw it and move on.

To learn awk, read the book Effective Awk Programming, 4th Edition, by Arnold Robbins.