首页 > 解决方案 > 替换/删除 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

标签: pythonbashawksed

解决方案


在本机 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
}

推荐阅读