Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

print $NF gives incorrect result 1

Status
Not open for further replies.

er13b6ac

Programmer
Jun 3, 2002
5
US
I have an Awk script that behaves correctly from a command prompt but differently in a Makefile
the script is:

pwd | awk 'BEGIN {FS="/"}{print NF} {print $NF}'

from the command prompt, NF gives the field count and $NF correctly gives the last field.
from the makefile, NF gives the correct field count, but $NF
prints the entire path as one field.

 
linux gawk 3.0.98
function basename_awk() {
echo -e `pwd` | awk ' BEGIN {
FS = "/"
}
{
print NF
print $NF
> }'
}
output:
3
mars

Seems okay here.
 
You need to "quote" the dollar sign in MAKE with another dollar sign, otherwise it thinks it starts one of its own variables.

That is:
Code:
--- Start of makefile
all:
         pwd | awk 'BEGIN {FS="/"}{print NF} {print $$NF}'
--- End of makefile
I'm not sure how to add a tab in this message, so I used spaces in front of the command. In real life those spaces must be a tab. The output is:
Code:
pwd | awk 'BEGIN {FS="/"}{print NF} {print $NF}'
4
tmp
If you place an atsign (@) in front of pwd (@pwd), then only the output will be displayed. Also, please note that your algorithm erroneously reports one more directory level than what exists. For example, /home/myid/tmp has three (3) directory levels, but the output from your AWK script shows it has four (4) fields. That is because the first field is empty. That may, or maynot be a problem, depending on what you are trying to accomplish.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top