按模式解析,Sed

时间:2015-06-26 07:47:51

标签: bash sed

我想解析mikrotik的价值,这就是我得到的: 但是,当我检查IP 192.168.10.5中没有主机名时

active-address=192.168.10.1
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="oXXXXX" 
active-address=192.168.10.2 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="ZXXXXX" 
active-address=192.168.10.3 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="OXXXXX" 
active-address=192.168.10.4 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="AXXX" 
active-address=192.168.10.5 
active-mac-address=XX:XX:XX:XX:XX:XX 
active-address=192.168.10.6 <-- This is should be host-name
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="TXXXX" 

我想在IP 192.168.10.5的mac-address之后添加字符串host-name="-" 模式总是那样......

active-address=192.168.10.1
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="oXXXXX" 
active-address=192.168.10.2 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="ZXXXXX" 
active-address=192.168.10.3 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="OXXXXX" 
active-address=192.168.10.4 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="AXXX" 
active-address=192.168.10.5 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="-" <--- I want to append
active-address=192.168.10.6
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="TXXXX" 

我该怎么做?

2 个答案:

答案 0 :(得分:1)

通用sed将找到所有缺少的主机名,并假设所有主机都有活动的mac地址。

sed '/active-mac-address/{N;/host-name/!s/\n/\nhost-name="-"\n/}' file

如Ed所指出的,这将在solaris上死亡,并且不会与文件的最后一行匹配。

答案 1 :(得分:1)

sed用于单行上的简单替换,即全部。所有的arcnae单字符sed构造在1970年代中期发明时都已经过时了。

只需使用awk的清晰度,简洁性,健壮性,可扩展性以及软件的大多数其他理想属性:

let guess: u32 = guess.trim().parse().unwrap();

请注意,无论缺少的主机名是否来自文件的末尾,上述内容都将起作用:

$ cat tst.awk
/^active-address/ { prtRec() }
{ rec = rec $0 ORS }
END { prtRec() }

function prtRec() {
    if (rec != "") {
        rec = rec (rec~/host-name/ ? "" : "host-name=\"-\"\n")
        printf "%s", rec
        rec = ""
    }
}

$ awk -f tst.awk file
active-address=192.168.10.1
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="oXXXXX" 
active-address=192.168.10.2 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="ZXXXXX" 
active-address=192.168.10.3 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="OXXXXX" 
active-address=192.168.10.4 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="AXXX" 
active-address=192.168.10.5 
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="-"
active-address=192.168.10.6
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="TXXXX"

想要以CSV或任何其他形式输出?只需对打印记录的函数进行一些调整,例如:

$ cat file2
active-address=192.168.10.6
active-mac-address=XX:XX:XX:XX:XX:XX 
$ 
$ awk -f tst.awk file2
active-address=192.168.10.6
active-mac-address=XX:XX:XX:XX:XX:XX 
host-name="-"