使用 sed 删除两个匹配模式之间的所有行 [英] Using sed to delete all lines between two matching patterns

查看:57
本文介绍了使用 sed 删除两个匹配模式之间的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的文件:

# ID 1
blah blah
blah blah
$ description 1
blah blah
# ID 2
blah
$ description 2
blah blah
blah blah

如何使用 sed 命令删除 #$ 行之间的所有行?所以结果会变成:

How can I use a sed command to delete all lines between the # and $ line? So the result will become:

# ID 1
$ description 1
blah blah
# ID 2
$ description 2
blah blah
blah blah

能否请您也解释一下?

推荐答案

使用这个 sed 命令来实现:

Use this sed command to achieve that:

sed '/^#/,/^\$/{/^#/!{/^\$/!d}}' file.txt

Mac 用户(为了防止 d 命令末尾的多余字符 错误)需要在右括号前添加分号

Mac users (to prevent extra characters at the end of d command error) need to add semicolons before the closing brackets

sed '/^#/,/^\$/{/^#/!{/^\$/!d;};}' file.txt

输出

# ID 1
$ description 1
blah blah
# ID 2
$ description 2
blah blah
blah blah

说明:

  • /^#/,/^\$/ 将匹配以 # 开头的行与以 $ 开头的行之间的所有文本.^ 用于行首字符.$ 是一个特殊字符,需要转义.
  • /^#/! 表示如果行首不是 #
  • /^$/! 表示如果行首不是 $
  • d 表示删除
  • Explanation:

    • /^#/,/^\$/ will match all the text between lines starting with # to lines starting with $. ^ is used for start of line character. $ is a special character so needs to be escaped.
    • /^#/! means do following if start of line is not #
    • /^$/! means do following if start of line is not $
    • d means delete
    • 所以总的来说,它首先匹配从 ^#^\$ 的所有行,然后从那些匹配的行中查找不匹配的行 ^#不匹配 ^\$ 并使用 d 删除它们.

      So overall it is first matching all the lines from ^# to ^\$ then from those matched lines finding lines that don't match ^# and don't match ^\$ and deleting them using d.

      这篇关于使用 sed 删除两个匹配模式之间的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆