python - 替换/删除 Bash 中其他两行之间的行

标签 python bash awk sed

我有一个 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/

相关文章:

python - 最小化多变量函数 Python SciPy

Python:更新频率表(以列表列表的形式)

Python Rest API POST 图像

bash - 使用Bash循环删除未分配的Graylog2索引/碎片

linux - 在单个命令中使用变量在 grep 多个结果上附加字符串

python - 如何通过 ssh 命令行转义远程命令的引号

python - Amazon EC2 Django 静态文件配置

bash - 在 Bash 中删除 Unicode 行分隔符 "U+2028"

linux - Bash,Linux,需要根据另一个文件中的匹配内容从一个文件中删除行

bash - 添加从命令输出中提取的时间的分钟