![转换文件以便仅打印主机名和 IP](https://linux22.com/image/125248/%E8%BD%AC%E6%8D%A2%E6%96%87%E4%BB%B6%E4%BB%A5%E4%BE%BF%E4%BB%85%E6%89%93%E5%8D%B0%E4%B8%BB%E6%9C%BA%E5%90%8D%E5%92%8C%20IP.png)
我需要将以下文件示例 1 转换为显示的文件示例2
所以它会打印机器名称和IP,但仅限于“name”出现在host_name之前的情况
- redhat03.rdns.com 10.10.29.66 未打印,因为“name”未出现在 host_name 之前
请建议通过 awk 或 sed 或 perl oneliners 进行此转换的最佳方法是什么
例子1
"name" : "REDHAT",
"host_name" : "linux01.rdns.com",
"ip" : "10.10.29.61"
"name" : "REDHAT",
"host_name" : "linux02.rdns.com",
"ip" : "10.10.29.62"
"name" : "REDHAT",
"host_name" : "linux03.rdns.com",
"ip" : "10.10.29.63"
"name" : "REDHAT",
"host_name" : "redhat01.rdns.com",
"ip" : "10.10.29.64"
"name" : "REDHAT",
"host_name" : "redhat02.rdns.com",
"ip" : "10.10.29.65"
"name" : "REDHAT",
"host_name" : "redhat03.rdns.com",
"ip" : "10.10.29.66"
"host_name" : "redhat04.rdns.com",
"ip" : "10.10.29.67"
"name" : "REDHAT",
"host_name" : "redhat05.rdns.com",
"ip" : "10.10.29.68"
"name" : "REDHAT",
"host_name" : "redhat06.rdns.com",
"ip" : "10.10.29.81"
"name" : "REDHAT",
"host_name" : "redhat07.rdns.com",
"ip" : "10.10.29.82"
"name" : "REDHAT",
"host_name" : "redhat08.rdns.com",
"ip" : "10.10.29.83"
"name" : "REDHAT",
"host_name" : "redhat09.rdns.com",
"ip" : "10.10.29.84"
预期成绩
linux01.rdns.com 10.10.29.61
linux02.rdns.com 10.10.29.62
linux03.rdns.com 10.10.29.63
redhat01.rdns.com 10.10.29.64
redhat02.rdns.com 10.10.29.65
redhat03.rdns.com 10.10.29.66
redhat05.rdns.com 10.10.29.68
redhat06.rdns.com 10.10.29.81
redhat07.rdns.com 10.10.29.82
redhat08.rdns.com 10.10.29.83
redhat09.rdns.com 10.10.29.84
答案1
awk
解决方案:
awk '/ip/ && NR-1==h_num && NR-2==n{
r=h" "$3; gsub(/[,"]+/, "", r); print r
}
/"host_name"/{ h_num=NR; h=$3 }
/"name"/{ n=NR }' file
输出:
linux01.rdns.com 10.10.29.61
linux02.rdns.com 10.10.29.62
linux03.rdns.com 10.10.29.63
redhat01.rdns.com 10.10.29.64
redhat02.rdns.com 10.10.29.65
redhat03.rdns.com 10.10.29.66
redhat05.rdns.com 10.10.29.68
redhat06.rdns.com 10.10.29.81
redhat07.rdns.com 10.10.29.82
redhat08.rdns.com 10.10.29.83
redhat09.rdns.com 10.10.29.84
答案2
以下内容awk
可能会对您有所帮助。
awk -F' +|:|,|"' '/"name"/{flag=1;next} flag && /"host_name"/{val1=$(NF-2);next} flag && /"ip"/{print val1,$(NF-1);flag=""}' Input_file
答案3
请找到下面的 sed oneliner 以获得结果。经检查其工作正常
sed -n '/host_name/,+1p' filename | awk -F ":" '{print $2}' | sed 's/"//g' |sed "s/,//g" | sed "N;s/\n/ /g"
输出
linux01.rdns.com 10.10.29.61
linux02.rdns.com 10.10.29.62
linux03.rdns.com 10.10.29.63
redhat01.rdns.com 10.10.29.64
redhat02.rdns.com 10.10.29.65
redhat03.rdns.com 10.10.29.66
redhat04.rdns.com 10.10.29.67
redhat05.rdns.com 10.10.29.68
redhat06.rdns.com 10.10.29.81
redhat07.rdns.com 10.10.29.82
redhat08.rdns.com 10.10.29.83
redhat09.rdns.com 10.10.29.84
答案4
这是另一个 awk 解决方案
awk -F'|:|,|"' '/"name"/{getline; printf $5; getline; print " "$5}' file1