Este 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"'
produz:
-----
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",
Primeiro, extrai todas as sub-rotinas que contêm "cluster_name". Ele faz isso extraindo estrofes que são regiões (ou windows: -w, + w) "href" .. "ip". A partir desse subconjunto, um grep normal extrai as linhas desejadas correspondentes a "host_name".
Esse esquema permite que as linhas "cluster_name" e "host_name" apareçam em qualquer lugar da sub-rotina, mesmo em posições relativas diferentes, como na sub-rotina adicional "worker06".
Feito em um sistema como:
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
Alguns detalhes para o 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)
Felicidades ... felicidades, drl