【问题标题】:regex to exclude string and delete line正则表达式排除字符串并删除行
【发布时间】:2021-05-31 12:30:21
【问题描述】:

我在一个 XML 文件中有以下几行

<User id="10338" directoryId="1" sometext txt text test/>
<User id="10359" directoryId="100" some more text text text/>
<User id="103599" directoryId="100" some more text text text/>
<User id="10438" directoryId="1" sometext txt text test/>

我正在尝试删除以 User id=" 开头的所有行,但我想保留那些具有 directoryId="1" 的行

我当前的 sed 命令是

sed -i '' '/<User id="/d' file.xml

我查看了A regular expression to exclude a word/string 和其他一些堆栈溢出帖子,但无法使其正常工作。请有人帮我写正则表达式。我基本上需要删除所有以 的行

【问题讨论】:

  • 试试sed -i '' -e '/directoryId="1"/b' -e '/&lt;User id="/d' file.xml
  • Don't Parse XML/HTML With Regex. 我建议使用 XML/HTML 解析器 (xmlstarlet, xmllint ...)。

标签: regex xml sed


【解决方案1】:

你可以使用

sed -i '' -e '/directoryId="1"/b' -e '/<User id="/d' file.xml

使用这个 sed 命令,

  • /directoryId="1"/b 跳过包含 directoryId="1" 和的行
  • /&lt;User id="/d 删除包含&lt;User id=" 的其他行。

查看online demo

【讨论】:

    猜你喜欢
    • 2012-02-17
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2017-04-13
    • 1970-01-01
    • 2016-04-03
    相关资源
    最近更新 更多