【问题标题】:regex in bash-script to exclude certain wordbash脚本中的正则表达式以排除某些单词
【发布时间】:2016-05-02 13:17:58
【问题描述】:

我想排除“cgs”和“CGS”,但选择所有其他数据。

测试数据:

排除这个-->

C

SP999_20151204080019_0054236_000_CGS.csv
CSP999_20151204080019_0054236_000_cgs.csv

接受所有其他。

我尝试过类似.*([Cc][Gg][Ss]).* 的方法来选择cgs,但我不明白排除的东西=)它必须是没有grep 的filename_pattern。

亲切的问候,

鲍比

【问题讨论】:

  • 您可以使用 awk 和 [Cc][Gg][Ss] 作为字段分隔符。
  • grep -v cgs(-v 表示排除)或使用 egrep(表示正则表达式)。
  • if [[ "${short_filename}" =~ ${regex} ]] # all exclude cgs then local out_target="${intern_file/${in_dir}/${out_dir}}" fi 因此我只需要没有 grep 的正则表达式等等

标签: regex linux bash shell regex-negation


【解决方案1】:

必须成为正则表达式吗?如果您在脚本中设置,您可以使用 glob 模式轻松完成此操作

shopt -o extglob

启用扩展通配符。然后,您将使用该模式

!(*[Cc][Gg][Ss]*)

生成名称中没有 CGS 的所有条目。

【讨论】:

    【解决方案2】:
    grep --invert-match --ignore-case cgs < filenames_list
    

    【讨论】:

    • @Soren,OP 在这一点上似乎有点含糊,(他的描述如你所述,但他的代码另有说明),因此允许 cGs 溜走似乎过于字面意思。
    • 我不认为这是模糊的——他想匹配和排除任何带有“cgs”和“CGS”的东西
    • @user3181885 您能否说明您是否要排除cGs
    • 嗨,我有我的正则表达式的解决方案 --> *[^:CGS|cgs:].* 这个正则表达式排除了我的 testdata 中的所有 CGS 或 cgs =) 感谢您的帮助
    • @user3181885,很高兴听到这个消息,但您最初是否想排除 cGs 更像是一个“是”或“否”的问题。或者换一种说法,你最初是否考虑过输入数据包含 cGs 的可能性?好奇的人想知道......
    【解决方案3】:

    extglob 选项

    试试这个:

    ls -ld $path/!(*[cC][gG][sS].csv)
    

    然后看看

    man -Pless\ +/extglob bash
    
      If the extglob shell option is enabled using the shopt builtin, several
      extended  pattern  matching operators are recognized.  In the following
      description, a pattern-list is a list of one or more patterns separated
      by a |.  Composite patterns may be formed using one or more of the fol‐
      lowing sub-patterns:
    
             ?(pattern-list)
                    Matches zero or one occurrence of the given patterns
             *(pattern-list)
                    Matches zero or more occurrences of the given patterns
             +(pattern-list)
                    Matches one or more occurrences of the given patterns
             @(pattern-list)
                    Matches one of the given patterns
             !(pattern-list)
                    Matches anything except one of the given patterns
    

    【讨论】:

      【解决方案4】:

      以下内容可能对您有所帮助:

      ls |grep -iEv "cgs" 
      

      【讨论】:

        【解决方案5】:

        使用 grep 的反转匹配:

        grep -v 'cgs\|CGS' <filelist
        

        或者,

        ls | grep -v 'cgs\|CGS'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-09
          • 2019-04-30
          • 2018-08-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多