我正在尝试遍历配置文件中包含的 IP 列表,但我需要剪切行,因为我只需要 IP 和 conf=/path/to/file,所以我可以将它们放入数组或变量中进行进一步处理。
问题是,当将管道添加到命令替换中的“cut -d$'\n' -f1,3”时,for 循环将只对“check”数组列表中的 IP 进行一次迭代。底部的期望结果:
check=(
"192.168.0.50"
"192.168.0.100"
"192.168.0.150"
"192.168.0.200"
)
for i in "${check[@]}"; do
ip="$i"
# config=$(grep -A2 "$ip" /home/user/D1/serverfault/config_file)
config=$(grep -A2 "$ip" /home/user/D1/serverfault/config_file | cut -d$'\n' -f1,3)
if [ -z "$config" ]; then
echo "$ip NOT IN CONFIG"
else
echo "$config"
fi
done
### config_file contents ###
192.168.0.50
255.255.255.0
conf=/path/to/company/app/server001
logging=yes
-----
192.168.0.100
255.255.255.0
conf=/path/to/company/app/cluster
logging=yes
-----
192.168.0.50
255.255.255.0
conf=/path/to/company/app/server005
logging=yes
-----
192.168.0.150
255.255.255.0
conf=/path/to/company/app/server006
logging=yes
DESIRED RESULTS 2 passes produced in results for 192.168.0.50
192.168.0.50
conf=/path/to/company/app/server001
-----
192.168.0.50
conf=/path/to/company/app/server005
-----
192.168.0.100
conf=/path/to/company/app/cluster
-----
192.168.0.150
conf=/path/to/company/app/server006
Please tell me how I can fix these.
答案1
awk
处理这样的文件可能更简单吗?
该line
变量控制 IP 地址输出。脚本匹配 IP 地址行,但只打印出第一行。如果处理的行以“conf=”开头,则打印该行和“-----”行)。
awk 'BEGIN{IP_line=1}
/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/ && IP_line==1 {
print
IP_line=2
}
/^conf=/ {
print
print "-----"
IP_line=1
}' /home/user/D1/serverfault/config_file