我有一个 Linux 设备树文件:
# Other content
...
&uart3 {
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_uart3>;
status = "okay";
};
# Other content
...
首先我想提取&uart3
和};
之间的行,这是UART3节点,使用sed
:
sed -n '/^&uart3/,${p;/^};/q}' uart3.dts
输出是:
&uart3 {
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_uart3>;
status = "okay";
};
我的问题是如何删除 &uart3
和 };
之间的所有行,或者有没有办法用其他内容替换它们。
我阅读了有关检测匹配并引发特定标志的 awk
解决方案 here 。
但我不明白如何实现这一目标。
我不会在这里解析设备树,因此不需要 dtc 库,
我仅将文件作为文本文件处理。
由于这会遇到 Yocto 配方,因此解决方案也可以使用 Python
。
最佳答案
这是我回答的最常见问题的一个变体,哈哈
$: cat file
# Other content
...
&uart3 {
pinctrl-names = "default";
pinctrl-0 = <&pinctrl_uart3>;
status = "okay";
};
# Other content
...
$: cat replacement.txt
This is what I want there instead.
I just stuck it over here in this other file.
$: cat tst
sed '/^&uart3 {/,/^};/{
/^&uart3 {/{ p; r replacement.txt
}
/^};/!d;
}' file
$: ./tst
# Other content
...
&uart3 {
This is what I want there instead.
I just stuck it over here in this other file.
};
# Other content
...
/^&uart3 {/,/^};/{
在从 ^&uart3 {
到下一个 ^ 的匹配范围内的任何行上打开一个 block };
下一点有一个问题 - 不要在文件名后的同一行上放置任何内容。
/^&uart3 {/{ p; r replacement.txt
}
这表示如果我们正在查看的行是 ^&uart3 {
,则打开一个 block -
首先p
打印它,然后r
写入replacement.txt
的内容。
不过,在大多数实现中,您必须关闭下一行的 block ,因此它不会认为 curl 是文件名的一部分并破坏语法。
/^};/!d;
表示 block 的其余部分,除非 (!
) 它是结束 curl ,只是d
删除它。
#编辑
如果您想在没有文件的情况下执行此操作 -
$: cat tst
sed '/^&uart3 {/,/^};/{
/^&uart3 {/{ p; a\
This is what I want there instead.\
There is no other file.
}
/^};/!d;
}' file
$: ./tst
# Other content
...
&uart3 {
This is what I want there instead.
There is no other file.
};
# Other content
...
参见https://www.gnu.org/software/sed/manual/sed.html#Other-Commands
一切都在那里。 :)
关于python - 替换/删除 Bash 中其他两行之间的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68366714/