【问题标题】:Regex Stop at the First Occurrence of a Word正则表达式在单词第一次出现时停止
【发布时间】:2021-01-26 03:36:29
【问题描述】:

如何将我的正则表达式更改为在单词的第一个匹配后停止?

我的文字是:

-rwxr--r-- 1 bob123 bob123 0 Nov 10 22:48 /path/for/bob123/dir/to/file.txt

有一个变量叫owner,cmd的第一个arg:

owner=$1

我的正则表达式是:^.*${owner}

我的比赛最终是:

-rwxr--r-- 1 bob123 bob123 0 Nov 10 22:48 /path/for/bob123

但我只希望它是:-rwxr--r-- 1 bob123

【问题讨论】:

    标签: regex bash regex-greedy


    【解决方案1】:

    通过添加问号:^.*?${owner}。这将使* 量词非贪婪。但是使用 -P 选项:grep -P 来使用 Perl 兼容的正则表达式。

    https://regex101.com/r/ThGpcq/1.

    【讨论】:

      【解决方案2】:

      这里不需要正则表达式,使用字符串操作和连接:

      text='-rwxr--r-- 1 bob123 bob123 0 Nov 10 22:48 /path/for/bob123/dir/to/file.txt'
      owner='bob123'
      echo "${text%%$owner*}$owner"
      # => -rwxr--r-- 1 bob123
      

      请参阅online Bash demo

      ${text%%$owner*} 从字符串末尾删除尽可能多的文本(由于 %%)直到并包括 $owner,并且 - 由于删除了 $owner 文本 - "...$owner" 添加了 @ 987654328@回。

      【讨论】:

        猜你喜欢
        • 2016-09-28
        • 1970-01-01
        • 2012-07-03
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        相关资源
        最近更新 更多