【问题标题】:Sed + Regex which will match any line except those that start with a backtickSed + Regex 将匹配除以反引号开头的任何行
【发布时间】:2020-09-04 23:42:30
【问题描述】:

我正在尝试提出一个 sed 语句,该语句将匹配正则表达式以包含不以反引号 ` 开头的每一行。

目标是在不以反引号开头的每一行添加一些内容。

反引号可以在行首或前面有一个或多个空格(或制表符),我需要匹配的任何其他行,即使是有反引号的行不是一开始。

这是我目前所拥有的:

cat myfile.txt
`this line starts with backtick`

  `this one does too, but there are some spaces`

!some stuff on May 14 19:52:58 2020

more stuff *(&) 243123123123
  indented stuff
  indented stuff

string here that is nothing special
*here is an asterisk

  match `this line`
  1 number one
  2 number two

 `ignore this one`

这是我的 sed 表达式(在 Mac 上)。

sed -e 's/^\([^[\s*`].*\)/--matched--\1/g' myfile.txt

`this line starts with backtick`

--matched--  `this one does too, but there are some spaces`

--matched--!some stuff on May 14 19:52:58 2020

--matched--more stuff *(&) 243123123123
--matched--  indented stuff
--matched--  indented stuff

string here that is nothing special
*here is an asterisk

--matched--  match `this line`
--matched--  1 number one
--matched--  2 number two

--matched-- `ignore this one`

编辑:清晰度

【问题讨论】:

    标签: macos sed regex-negation regexp-replace


    【解决方案1】:

    最简单的方法是匹配你想忽略的那些,然后否​​定匹配。这是一种符合 POSIX 的方法:

    sed --posix '/^[[:space:]]*`/!{/^$/!s/^/--matched---/}' ./myfile.txt
    

    概念证明

    $ sed --posix '/^[[:space:]]*`/!{/^$/!s/^/--matched---/}' ./myfile.txt
    `this line starts with backtick`
    
      `this one does too, but there are some spaces`
    
    --matched---!some stuff on May 14 19:52:58 2020
    
    --matched---more stuff *(&) 243123123123
    --matched---  indented stuff
    --matched---  indented stuff
    
    --matched---string here that is nothing special
    --matched---*here is an asterisk
    
    --matched---  match `this line`
    --matched---  1 number one
    --matched---  2 number two
    
      `ignore this one`
    

    【讨论】:

    • 谢谢,我真正想做的是在每一行(不以`开头)前面加上别的东西。我可能可以采用这种方法并分两步完成,但我希望一次完成。
    • @yeahb2018 更新了我的概念证明,以展示如何做到这一点。
    • “概念证明”适用于正确的解决方案,这不是您第一行的内容。第一行使用-n 标志和p 命令 - 不是概念证明中的(正确)解决方案所做的。
    • 感谢@SiegeX 这在 Linux 中运行良好,但看起来我的 mac 不喜欢它(BSD)。我会做一些研究,但至少在 Linux (GNU) 上它完全符合我的需要。
    • @yeahb2018 嗯,不知道为什么会这样,我使用的命令是 POSIX 兼容的。您可以通过在调用sed 之后直接添加--posix 选项来检查自己(在Linux 上)。您仍然应该得到相同的输出。 BSD sed 告诉你什么?
    【解决方案2】:

    这可能对你有用(GNU sed):

    sed  '/^\s*$\|^\s*`/!s/^/--matched--/' file
    

    如果该行为空(也可能只包含空格)或第一个非空格字符是勾号,则不要在前面加上 --matched--

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 2023-03-04
      • 2019-08-06
      • 2020-04-09
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多