AWK - input variable to pattern from SHELL -
AWK - input variable to pattern from SHELL -
i extract text file using awk basicly works correctly create dymamical using variable looking pattern.
how should works:
file test_input contains (btw: extract hp dp omnimm -show_locked_devs
)
type: device name/id: drive1 pid: 28405 host: host1 type: cartridge name/id: lib1 pid: 28405 host: host1 location: 47 ...
get "pid" number drive1 => command find pattern (drive1) , display next line file test_input (28405) cat test_input | awk 'c&&!--c;/drive1/{c=1}'| awk '{print $2}' 28405
cat test_input | awk 'c&&!--c;/28405/{c=2; print $0}'| grep location | awk '{print $2}' 47
i have noticed double quotes in awk can handle shell variables when utilize same command in script have got error message "awk: statement cannot correctly parsed."
drive=drive1;cat test_input | awk "c&&!--c;/$drive/{c=1}" | awk '{print $2}' 28405
if have hints how work variables shell please allow me know. know commands , redirections complicated yeah not script master :)
if need utilize environment variables can utilize environ
awk built-in hash. if want pass arguments awk, can utilize -v
option.
an illustration both:
cat >inputfile <<eot aaa bbbxxx xxxccc ddd eot var=xxx awk -vvar="$var" '$0~var {print environ["user"]":"$0}' inputfile
i added creation of sample inputfile
.
as know in awk version white space needed between -v
, var
.
if may suggest utilize '
instead of "
around whole script line. makes life bit easier if utilize lot of awk.
output:
myuser:bbbxxx myuser:xxxccc
if understood well, need collect names of devices , locations in non "device" blocks. assume clock starting tag type
, tag order same. if not, pls. inform me. based on these assumptions code looks like:
awk '$1=="type:"{dev=$2=="device"} dev && $1=="name/id:"{name=$2} dev && $1=="pid:"{pids[name]=$2} !dev && $1=="pid:"{pid=$2} !dev && $1=="location:"{locs[pid]=$2} end { for(i in pids) { pid = pids[i]; print i"\t"(pid in locs ? locs[pid] : "none"); } } ' inputfile
it fills pids
, and locs
hash, prints device names found in pids
hash , location belongs pid (if found).
output:
drive1 47
of course of study if location after device block, line printed when location found. end
part dropped.
shell variables awk scripting
Comments
Post a Comment