小编mar*_*w18的帖子

在文件中的两个正则表达式模式之间增量交换行

我正在尝试使用 bash 脚本对文件进行一些文本处理。目标是将所有以“field:”开头的行缩进到“attribute:”标签下,并将它们与后面以“- attr:”开头的相关行交换。

到目前为止,我认为我有应该与标签匹配的正则表达式模式:

/ *field:(.*)/g

/ *- attr:(.*)/g

但是我在解析所需字段并使它们正确交换的逻辑方面没有取得任何成功。

示例输入文本

- metric: 'example.metric.1'
  attributes:
      field: 'example 1'
    - attr: 'example1'
      field: 'example 2'
    - attr: 'example2'
      field: 'example 3'
    - attr: 'example3'
      field: 'example 4'
    - attr: 'example4'
- metric: 'example.metric.2'
  attributes:
      field: 'example 5'
    - attr: 'example5'
      field: 'example 6'
    - attr: 'example6'
      field: 'example 7'
    - attr: 'example7'
- metric: 'example.metric.3'
...
Run Code Online (Sandbox Code Playgroud)

期望输出

- metric: 'example.metric.1'
  attributes:
    - attr: 'example1'
      field: 'example 1'
    - attr: 'example2' …
Run Code Online (Sandbox Code Playgroud)

sed awk python shell-script

5
推荐指数
1
解决办法
176
查看次数

标签 统计

awk ×1

python ×1

sed ×1

shell-script ×1