Yes, gawk
can do this, set the record separator to \0
. For example, the command
gawk 'BEGIN { RS="\0"; FS="=" } $1=="LD_PRELOAD" { print $2 }' </proc/$(pidof mysqld)/environ
Prints the value of the LD_PRELOAD
variable:
/usr/lib/x86_64-linux-gnu/libjemalloc.so.1
The /proc/$PID/environ
file is a separate list of NUL
environment variables. I use this as an example since it is easy to try on a Linux system.
The BEGIN
part sets the record separator to \0
, and the field separator to =
, because I also want to extract the part after =
based on the part before =
.
$1=="LD_PRELOAD"
starts the block if there is a key in the first field that interests me.
The print $2
block prints the line after =
.
But mawk
cannot parse input files separated by NUL
. This is documented in man mawk
:
BUGS mawk cannot handle ascii NUL \0 in the source or data files.
mawk
stop reading input after the first character \0
.
You can also use xargs
to handle NUL
shared input, a little unintuitively, like here:
xargs -0 -n1 </proc/$$/environ
xargs
uses echo
as the default command. -0
sets the input to split NUL
. -n1
sets the maximum value of the echo
arguments to 1, so the output will be separated by a newline.
And, as Graeme's answer shows, sed
can do this too.