AWKステートメントは、$ ip変数を使用して各行を検索しますが、構成には見つからないipを見つけるには、ELSEステートメントに$ ip NOT FOUND変数を印刷する必要があります。
IF ELSEと連携できず、ELSEステートメントで$ ip変数を再利用できないため、999.999.999.999 NOT IN CONFIGが印刷されます。
また、可能であれば、重複したgetline getline getlineを使用しないでください。たとえば、3行をスキップする方法はありますか?
declare -a iplist=(
"192.168.0.10"
"192.168.0.20"
"192.168.0.30"
"999.999.999.999"
)
for ip in "${iplist[@]}"; do
awk "/$ip/" '{if {print $0; getline; getline; getline; print $0; print "-----"} else {print "/$ip/" "NOT FOUND"}' /home/user/D1/config
### BELOW WORKS - But, need the IF ELSE Statement ###
awk "/$ip/"'{print $0; getline; getline; getline; print $0; print "-----"}' /home/user/D1/config
done
構成ファイルの内容:
ip=192.168.0.10
mask=255.255.255.0
allow=on
text=off
path=/home/user/D1/test/server1
-----
ip=192.168.0.20
mask=255.255.255.0
allow=on
text=off
path=/home/user/D1/test/server1
-----
ip=192.168.0.30
mask=255.255.255.0
allow=on
text=off
path=/home/user/D1/test/server1
-----
希望の出力:
ip=192.168.0.10
path=/home/user/D1/test/server1
-----
ip=192.168.0.20
path=/home/user/D1/test/server1
-----
ip=192.168.0.30
path=/home/user/D1/test/server1
-----
ip=192.168.0.30
path=/home/user/D1/different-path-than-line-above/server1
-----
ip=999.999.999.999 NOT IN CONFIG
-----
ベストアンサー1
正しい方法は、IPリストを使用してawkを一度呼び出して、値(f[]
下)のラベル/名前の配列を作成し、名前でのみ値にアクセスすることです。シェルループ(非常に遅い)もなく、getlineもありません(参照)。http://awk.freeshell.org/AllAboutGetline一般に、これらの要件を避けるのが最善の理由:
$ cat tst.sh
#!/bin/env bash
declare -a iplist=(
'192.168.0.10'
'192.168.0.20'
'192.168.0.30'
'999.999.999.999'
)
awk -v iplist="${iplist[*]}" '
BEGIN {
split(iplist,tmp)
for (idx in tmp) {
ip = tmp[idx]
cnt[ip] = 0
}
OFS = "="
sep = "-----"
}
{
tag = val = $0
sub(/=.*/,"",tag)
sub(/^[^=]+=/,"",val)
f[tag] = val
}
$0 == sep {
ip = f["ip"]
if ( ip in cnt ) {
cnt[ip]++
print "ip", ip
print "path", f["path"]
print sep
}
delete f
}
END {
for (ip in cnt) {
if ( cnt[ip] == 0 ) {
print "ip", ip " NOT IN CONFIG"
print sep
}
}
}
' config
。
$ ./tst.sh
ip=192.168.0.10
path=/home/user/D1/test/server1
-----
ip=192.168.0.20
path=/home/user/D1/test/server1
-----
ip=192.168.0.30
path=/home/user/D1/test/server1
-----
ip=999.999.999.999 NOT IN CONFIG
-----
tag = val = $0
設定に依存するのではなく、etcを使用して値からラベルを分離します。FS="="
なぜなら、=
ラベルはUNIXディレクトリまたはファイル名に表示される可能性があり、したがってpath
。