This snippet:
# Utility functions: print-as-echo, print-line-with-visual-space.
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }
pl " Input data file $FILE:"
cat $FILE
pl " Expected output:"
cat $E
pl " Results:"
cgrep -D -w '"href"' +w '"ip"' "cluster_name" $FILE |
grep '"host_name"'
produces:
-----
Input data file data1:
"href" : "http://localhost:8080/api/v1/hosts/worker02.sys87.com",
"Hosts" :
"cluster_name" : "hdp",
"host_name" : "worker02.sys87.com",
"ip" : "23.67.32.65"
"href" : "http://localhost:8080/api/v1/hosts/worker03.sys87.com",
"Hosts" :
"cluster_name" : "hdp",
"host_name" : "worker03.sys87.com",
"ip" : "23.67.32.66"
"href" : "http://localhost:8080/api/v1/hosts/worker04.sys87.com",
"Hosts" :
"host_name" : "worker04.sys87.com",
"ip" : "23.67.32.67"
"href" : "http://localhost:8080/api/v1/hosts/worker05.sys87.com",
"Hosts" :
"cluster_name" : "hdp",
"host_name" : "worker05.sys87.com",
"ip" : "23.67.32.68"
"href" : "http://localhost:8080/api/v1/hosts/worker06.sys87.com",
"Hosts" :
"host_name" : "worker06.sys87.com",
"cluster_name" : "hdp",
"ip" : "23.67.32.69"
-----
Expected output:
"host_name" : "worker02.sys87.com",
"host_name" : "worker03.sys87.com",
"host_name" : "worker05.sys87.com",
-----
Results:
"host_name" : "worker02.sys87.com",
"host_name" : "worker03.sys87.com",
"host_name" : "worker05.sys87.com",
"host_name" : "worker06.sys87.com",
It first extracts all stanzas that contain "cluster_name". It does so by extracting stanzas that are regions (or windows: -w, +w) "href" .. "ip". From this subset, then a normal grep extracts the desired lines matching "host_name".
This scheme allows the lines "cluster_name" and "host_name" to appear anywhere in the stanza, even in different relative positions, such as in the additional stanza for "worker06".
Done on a system like:
OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution : Debian 8.9 (jessie)
bash GNU bash 4.3.30
cgrep ATT cgrep 8.15
Some details for cgrep:
cgrep shows context of matching patterns found in files (man)
Path : ~/executable/cgrep
Version : 8.15
Type : ELF 64-bit LSB executable, x86-64, version 1 (SYS ...)
Home : http://sourceforge.net/projects/cgrep/ (doc)
Best wishes ... cheers, drl
grep -B 1 'host_name' file | grep -A 1 'cluster_name' | grep 'host_name'?