python - 替换/删除 Bash 中其他两行之间的行
问题描述
我有这个文件,它是一个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";
};
我的问题是如何删除 and 之间的所有行&uart3
,};
或者有没有办法用其他内容替换它们。
我在这里阅读了关于awk
检测匹配和提高某些标志的解决方案。但我不明白如何实现这一点。
我没有在这里解析设备树,所以不需要 dtc 库,
我只将文件作为文本文件处理。
由于这将被运行到 Yocto 配方中,因此也可以使用解决方案Python
。
解决方案
在本机 bash 中:
retrieve_only_section() {
local start end reading
start=$1; end=$2; reading=0
while IFS= read -r line; do
if [[ $line = $start ]]; then
reading=1
elif [[ $line = $end ]]; then
reading=0
printf '%s\n' "$line"
continue
fi
(( reading )) && printf '%s\n' "$line"
done
}
...并且retrieve_only_section '&uart3 {' '};' <yourfile
将仅检索该部分。
同样,可以替换(( reading )) && printf '%s\n' "$line"
为(( reading )) || printf '%s\n' "$line"
仅打印该部分之外的内容。
要替换该部分,可以使用:
replace_section() {
local start end replacement in_section
start=$1; end=$2; replacement=$3; in_section=0
while IFS= read -r line; do
if (( ! in_section )) && [[ $line = $start ]]; then
in_section=1
elif (( in_section )) && [[ $line = $end ]]; then
in_section=0
printf '%s\0' "$replacement"
continue
fi
(( in_section )) || printf '%s\n' "$line"
done
}
推荐阅读
- ssis - SSIS-IR “没有活动的工作人员代理。”
- git - 无法推入 Github
- amazon-web-services - 亚马逊 ecs 服务中任务的“期望计数”是多少?
- angular - Angular - 使用 Jasmine 监视 HttpClient 中的链式方法
- c++ - Eigen3 类的模板特化
- php - 在 POST 请求中获取多个输入字段
- javascript - 通过 Javascript onmouseover 事件处理程序将列表框中的值正确显示到 DIV 元素中
- symfony - 通过 Easy Deploy Bundle SSH 部署 Symfony
- mysql - 如何连接不同表中的值 - mysql
- python - 计算机视觉 openCV2 pyautogui