fcm*_*fcm 8 sed awk text-processing
我需要编辑如下文件:
auto wlx00
allow-hotplug wlx00
iface wlx000 inet dhcp
iface wlx000 inet6 auto
post-up sysctl -w net.ipv6.conf.wlx000.accept_ra=2
auto wlx000
Run Code Online (Sandbox Code Playgroud)
目标是删除以 'iface...inet6' 开头的行,并删除接下来以空格开头的几行(可以没有或超过一个):
iface wlx000 inet6 auto
post-up sysctl -w net.ipv6.conf.wlx000.accept_ra=2
Run Code Online (Sandbox Code Playgroud)
并保持其余部分不变以获得以下结果:
auto wlx00
allow-hotplug wlx00
iface wlx000 inet dhcp
auto wlx000
Run Code Online (Sandbox Code Playgroud)
我尝试使用 sed 如下:
sed -i.old -r -e "/iface\s*\w*\s*inet6.*/,\${d;/^\s.*/d;}" /etc/configfile
Run Code Online (Sandbox Code Playgroud)
但它会从正确的位置开始删除所有内容,但会删除到最后。我只想删除 select iface 文本后以空格开头的行。
试试你的sed一个班轮的这种改编:
sed '/iface\s*\w*\s*inet6.*/,/^[^ ]/ {/^[^ i]/!d}' file
Run Code Online (Sandbox Code Playgroud)
它匹配从您的第一个模式到不以空格字符开头的第一行的范围,并删除以空格或“i”开头的行(对于前导iface)。需要重新考虑i在块之后是否需要。
看起来像这样:
sed -n '/iface\s*\w*\s*inet6.*/ {:L; n; /^[ ]/bL;}; p' file
Run Code Online (Sandbox Code Playgroud)
请尝试并报告。
sed使用显式循环删除行的标准脚本:
/^iface .* inet6/ {
:again
N
s/.*\n//
/^[[:blank:]]/b again
}
Run Code Online (Sandbox Code Playgroud)
脚本找到这些inet6行,然后在模式空间内部将下一行附加到该行(中间有一个嵌入的换行符)。然后它删除模式空间直到并包括第一个换行符(这将删除原始inet6行)。它会继续这样做,直到模式空间不以空白字符(空格或制表符)开头。
测试:
$ cat file
auto wlx00
allow-hotplug wlx00
iface wlx000 inet dhcp
iface wlx000 inet6 auto
post-up sysctl -w net.ipv6.conf.wlx000.accept_ra=2
auto wlx000
Run Code Online (Sandbox Code Playgroud)
$ sed -f script.sed <file
auto wlx00
allow-hotplug wlx00
iface wlx000 inet dhcp
auto wlx000
Run Code Online (Sandbox Code Playgroud)
人工数据测试:
$ cat file
something1
something2
iface have a inet6 here
delete me
me too
same here
something3
something4
iface more something inet6
be gone
skip this
something5
Run Code Online (Sandbox Code Playgroud)
$ sed -f script.sed <file
something1
something2
something3
something4
something5
Run Code Online (Sandbox Code Playgroud)
脚本作为“单行”:
sed -e '/^iface .* inet6/ {' -e ':a' -e 'N;s/.*\n//;/^[[:blank:]]/ba' -e '}'
Run Code Online (Sandbox Code Playgroud)