使用 shell 脚本删除一些文本?

Remove some text with shell scripts?

我想获得一些关于如何使用 cygwin 的帮助,它有 bash 到 shell 编写以下脚本:

我有一个包含以下内容的 txt 文件:

action "action1"
  reset
  type xformbin
  http-method-limited POST
  http-method-limited2 POST
exit

action "action2"
  reset
  admin-state disabled
  type results
  http-method-limited POST
  http-method-limited2 POST
exit

action "action3"
  reset
  admin-state disabled
  type setvar
  http-method-limited POST
  http-method-limited2 POST
exit

我希望可以编写一个 shell 脚本来删除 admin-state = disabled 的块?

所以,我希望我可以遍历 txt 文件,如果 admin-state = disabled,请从该特定块中删除 "action" 和 "exit" 之间的所有内容。

我希望示例文本的最终结果如下:

action "action1"
  reset
  type xformbin
  http-method-limited POST
  http-method-limited2 POST
exit

谢谢。

你有 perl 吗?

local $/="exit";
while (<>) {
    print if not /admin-state disabled/;
}

因此,如果中间有 'disabled',您希望忽略整个块,但如果没有,则打印出来。

sed -n '
  /action/,/exit/ {
  /action/ { x; d; }
  H;
  /exit/ { x;
    /disabled/ d;
    p;         d;
  }
}' x

除非在从 actionexit 的块中,否则这将不执行任何操作。在那些 -

如果一行有action,存储它并删除模式space以触发下一次读取。

否则将行附加到存储的保留 space。

如果该行有exit,

  • 将保持 space 换成模式 space
  • 如果采集到的花样有disabled,删除触发读取下一条记录;
  • 如果没有,则打印,然后删除,触发读取下一条记录。

输出:

$: sed -n '
  /action/,/exit/ {
    /action/ { x; d; }
    H;
    /exit/ { x;
      /disabled/ d;
      p;         d;
    }
  }' infile
action "action2"
reset
admin-state enabled
type xform
http-method GET
http-method-limited POST
http-method-limited2 POST exit

希望对您有所帮助。