gpt4 book ai didi

linux - 匹配两行,替换为三行

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:07:42 25 4
gpt4 key购买 nike

我需要使用 sedevery 匹配的两行模式替换为三行模式。这是我的输入文件 (tempfile.txt)。

lease 192.168.6.100 {
binding state free;
hardware ethernet 00:e0:4c:68:00:96;
}
lease 192.168.6.100 {
binding state active;
hardware ethernet 00:e0:4c:68:00:96;
client-hostname "andrew-H81M-S2PH";
}
lease 192.168.6.100 {
binding state free;
hardware ethernet 00:e0:4c:68:00:96;
}
lease 192.168.6.100 {
binding state active;
hardware ethernet 00:e0:4c:68:00:96;
client-hostname "andrew-H81M-S2PH";
}

基本上,如果 client-hostname "HOSTNAME"; 缺少,则应将其替换为 tab,然后是 newline

我的尝试:sed 'N;/硬件。*}/d; ; D'临时文件.txt

结果是:

lease 192.168.6.100 {
binding state free;
lease 192.168.6.100 {
binding state active;
hardware ethernet 00:e0:4c:68:00:96;
client-hostname "andrew-H81M-S2PH";
}
lease 192.168.6.100 {
binding state free;
lease 192.168.6.100 {
binding state active;
hardware ethernet 00:e0:4c:68:00:96;
client-hostname "andrew-H81M-S2PH";
}

这是我想要的输出。

lease 192.168.6.100 {
binding state free;
hardware ethernet 00:e0:4c:68:00:96;
<tab>
}
lease 192.168.6.100 {
binding state active;
hardware ethernet 00:e0:4c:68:00:96;
client-hostname "andrew-H81M-S2PH";
}
lease 192.168.6.100 {
binding state free;
hardware ethernet 00:e0:4c:68:00:96;
<tab>
}
lease 192.168.6.100 {
binding state active;
hardware ethernet 00:e0:4c:68:00:96;
client-hostname "andrew-H81M-S2PH";
}

如您所见, curl 之间始终存在三条线。这就是我的目标。

最佳答案

这就是诀窍(通过管道传输到 cat -A 以显示不可打印的字符):

$ sed -r 'N;s/^([[:space:]]*hardware.*)(\n})$/\1\n\t\2/;t;P;D' infile | cat -A
lease 192.168.6.100 {$
binding state free;$
hardware ethernet 00:e0:4c:68:00:96;$
^I$
}$
lease 192.168.6.100 {$
binding state active;$
hardware ethernet 00:e0:4c:68:00:96;$
client-hostname "andrew-H81M-S2PH";$
}$
lease 192.168.6.100 {$
binding state free;$
hardware ethernet 00:e0:4c:68:00:96;$
^I$
}$
lease 192.168.6.100 {$
binding state active;$
hardware ethernet 00:e0:4c:68:00:96;$
client-hostname "andrew-H81M-S2PH";$
}$

这不是删除匹配项,而是捕获应该围绕空行的两行并替换为换行符和制表符。我还添加了一些 anchor 以进行更安全的匹配。

这里涉及到一些技巧,因为模式空间在替换后包含两个换行符,但是 P;D 只打印第一行并开始一个新的循环,这也会导致不需要的换行符在包含 client-hostname 的行之后。

更详细的解释:

N       # Append next line to pattern space

# If the hostname is missing, insert a newline and a tab
s/^([[:space:]]*hardware.*)(\n})$/\1\n\t\2/

t # If we did the substitution, jump to end (prints complete pattern space)
P # Print first line in pattern space
D # Delete first line in pattern space - starts new cycle

关于linux - 匹配两行,替换为三行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com