awk: Alternate search method for special chars

The awk search (/string/…) requires that / be escaped as it is the delimiter for the search pattern. This can be a pain to fix for full pathnames:

awk -v MNT=/abc/def/file ‘/^MNT/{print $0}’

This fails as the imbedded slashes will be interpreted as more search delimiters. While you could insert escape characters like this:
awk -v MNT=i”/abc/def/file ‘/^MNT/{print $0}’

It is easier to use an imbedded procedure to compare like this

awk -v MNT=${MNT} ‘{if ($1==MNT) {print}}’

In this case, $1 is the first space-delimited string on the line which will act similarly to the ^MNT requirement (find the pathname only at the beginning of the line). Then $1==MNT is a straight text comparison with no escape needed for slashes.

An example of this can be found when parsing nfsstat -m which looks like this:

$ nfsstat -m
/mnt2 from atl4:/tmp (Addr
Flags: vers=2,proto=udp,auth=unix,hard,intr,dynamic…

All: srtt= 0 ( 0ms), dev= 0 ( 0ms), cur= 0 ( 0ms)

/mnt3 from atl1:/var/tmp/Packages (Addr

Flags: vers=3,proto=tcp,auth=unix,hard,intr,link,symlink…

All: srtt= 0 ( 0ms), dev= 0 ( 0ms), cur= 0 ( 0ms)

To locate the version for a given mountpoint, this will return the Flags for a selected mountpoint:

nfsstat -m |

awk -v MNT=${MNT} ‘{if ($1==MNT) {printf;getline;print}}’ |

cut -f 1,3 -d:

Result: vers=3,proto=tcp,auth=unix,hard,intr,link,symlink,…

The first part of the awk statement gets the line where /mnt3 is the first string. Then, printf is used to write the string WITHOUT a newline. getline pulls in the next line. This is concatenated with the first line so cut can now return the field after the first :char. Additional processing can be used to pull the vers=3 value. As a precaution to format changes, be sure to parse each flag to find vers= since it may be in the same order with changes to nfsstat.

Here is the complete code snippet to return the NFS version from $MNT

NFSLINE=$(nfsstat -m |
awk -v MNT=${MNT} ‘{if ($1==MNT) {printf;getline;print}}’ |

cut -f 1,3 -d:)

for NFSFLAG in $(echo “$NFSLINE” |
awk -F : ‘{print $2}’ | tr -s “,” ” “)


if [ $(echo $NFSFLAG | grep -ci vers=) -gt 0 ]


NFSVER=$(echo “$NFSFLAG” | cut -d= -f2)




$NFSVER will contain the version number.

– See more at: