1

I am trying to access a shell variable inside a piped nawk. I have never done this before and was wondering if its possible.

Here is the command sbdadm list-lu contents:

Found 2 LU(s)

          GUID                    DATA SIZE           SOURCE

600144f029bf0a0000004e0484740052 107380964864 /dev/rdsk/c9d0s1 600144f029bf0a0000004e0484740053 53694562304 /dev/rdsk/c9d0s3

Here is my sample of my script :

DISK=/dev/rdsk/c9d0s3
sbdadm list-lu |nawk '/$DISK/ {print}'

NOTE: I know the " /$DISK/" syntax will not work since $ is part of a regex symbol. I need the right syntax if such a code is ever possible.

In addition,does awk spawn another shell? If so, is it possible that I can export this variable $DISK to that shell.

tomkaith13
  • 1,717
  • 4
  • 27
  • 39

3 Answers3

1
export DISK=/dev/rdsk/c9d0s3
cat output | awk '$0 ~ ENVIRON["DISK"]{print}'

results:

600144f029bf0a0000004e0484740053 53694562304 /dev/rdsk/c9d0s3

With system call (after DISK was exported):

echo | awk '{system("echo $DISK")}'

results:

/dev/rdsk/c9d0s3

j.w.r
  • 4,136
  • 2
  • 27
  • 29
1

The problem is not that $ is part of RE syntax; it's that / is the RE delimiter. If you were just looking for c9d0s3, then using the proper quoting would do the trick:

$ DISK=c9d0s3
$ awk "/$DISK/ {print}" output
600144f029bf0a0000004e0484740053 53694562304 /dev/rdsk/c9d0s3

Explanation: if you use "" instead of '', then the shell variable would be expanded before handing the program to awk, so awk would see

/c9d0s3/ {print}

as its program. You can still search for a pattern with / in it, but it takes some shell quoting magic:

$ DISK=/dev/rdsk/c9d0s3
$ awk "{if (match(\$0, \"$DISK\")) print}" output
600144f029bf0a0000004e0484740053 53694562304 /dev/rdsk/c9d0s3

And no, awk does not spawn a subshell. Why would it? And why would you need one to pass a variable if you can just do it through the environment?

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • Since single quotes dint do the trick for me .. I assumed that the only reason $DISK wasnt visible was coz it was in another shell...Thanks for clarifying – tomkaith13 Jun 24 '11 at 20:03
1

In addition to j.w.r's answer, you can explicitly set an awk variable with the value of the shell variable:

 nawk -v disk="$DISK" '$3 == disk' output_file
Community
  • 1
  • 1
glenn jackman
  • 238,783
  • 38
  • 220
  • 352