【问题标题】:Regex with fswatch - Exclude files not ending with ".txt"带有 fswatch 的正则表达式 - 排除不以“.txt”结尾的文件
【发布时间】:2014-10-28 19:32:08
【问题描述】:

对于文件列表,我想匹配那些不以.txt 结尾的文件。我目前正在使用这个表达式:

.*(txt$)|(html\.txt$)

This expression will match everything ending in .txt, but I'd like it to do the opposite.


应该匹配:

happiness.html
joy.png
fear.src

应该 匹配:

madness.html.txt
excitement.txt

我想得到这个,这样我就可以和fswatch一起使用它:

fswatch -0 -e 'regex here' . | xargs -0 -n 1 -I {} echo "{} has been changed"

问题是它似乎不起作用。

PS:我使用标签 bash 而不是 fswatch,因为我没有足够的声望点来创建它。对不起!

【问题讨论】:

  • 你是在 BASH 中做这个吗?
  • 我已经更新了我的问题。我想用它作为 fswatch 的参数。

标签: regex bash fswatch


【解决方案1】:

尝试使用lookbehind,如下所示:

.*$(?<!\.txt)

Demonstration

基本上,只要最后 4 个字符不是".txt",它就匹配任何文本行。

【讨论】:

    【解决方案2】:

    您可以为此目的使用 Negative Lookahead。

    ^(?!.*\.txt).+$
    

    Live Demo

    您可以使用选项 -P 将此表达式与 grep 一起使用:

    grep -Po '^(?!.*\.txt).+$' file
    

    【讨论】:

      【解决方案3】:

      由于问题已标记为bash,因此可能不支持前瞻(grep -P 除外),这是一种不需要前瞻的grep 解决方案:

      grep -v '\.txt$' file
      happiness.html
      joy.png
      fear.src
      

      编辑:您可以使用此xargs 命令来避免匹配*.txt 文件:

      xargs -0 -n 1 -I {} bash -c '[[ "{}" == *".txt" ]] && echo "{} has been changed"'
      

      【讨论】:

      • 我已更新我的问题以添加更多上下文。我想用它作为 fswatch 的参数。
      • 非常感谢它似乎正在工作(虽然我已经将 != 更改为 == 所以它只匹配 txt 文件)
      • 确保仅匹配 .txt 使用 ==(已编辑)。很高兴它成功了。
      【解决方案4】:

      这真的取决于您使用的是什么正则表达式工具。许多工具提供了一种反转正则表达式含义的方法。例如:

      重击

      # succeeds if filename ends with .txt
      [[ $filename =~ "."txt$ ]]
      # succeeds if filename does not end with .txt
      ! [[ $filename =~ "."txt$ ]]
      # another way of writing the negative
      [[ ! $filename =~ "."txt$ ]]
      

      grep

      # succeeds if filename ends with .txt
      egrep -q "\.txt$" <<<"$filename"
      # succeeds if filename does not end with .txt
      egrep -qv "\.txt$" <<<"$filename"
      

      awk

      /\.txt$/ { print "line ends with .txt" }
      ! /\.txt$/ { print "line doesn't end with .txt" }
      $1 ~ /\.txt$/ { print "first field ends with .txt" }
      $1 !~ /\.txt$/ { print "first field doesn't end with .txt" }
      

      对于喜欢冒险的人来说,一个可以在任何 posix 兼容的正则表达式引擎中工作的 posix ERE

      /[^t]$|[^x]t$|[^t]xt$|[^.]txt$/
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-17
        • 1970-01-01
        • 2014-03-18
        • 1970-01-01
        • 2013-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多