【问题标题】:Using regex to search for a string pattern within a file before a , and after使用正则表达式在 a 之前和之后的文件中搜索字符串模式
【发布时间】:2019-05-02 22:04:04
【问题描述】:

我有一个很大的日志文件,我想从该文件中获取某些信息。 我正在尝试使用 grep 和 regex 来提取数据,但我没有得到任何结果。

单行格式为:

000.00.000.00,000,xxx,xxx.xxx.xxx,xxx

零 = 数字和 x = 一个字符

但我想要第二个','之后和最后一个','之前的所有内容

我一直在努力

grep [[a-zA-Z].\.[a-zA-Z].\.[a-zA-Z]]

各种各样,但我没有设法得到它

我希望得到:

','xxx.xxx.xxx','

但没有,

【问题讨论】:

    标签: regex unix grep


    【解决方案1】:

    使用 Perl:

    perl -ape 's/^.+?[a-z]+,([^,]+).*$/$1/i' file
    

    输出:

    xxx.xxx.xxx
    

    说明:

    s/              # substitute
      ^             # beginning of line
      .+?           # 1 or more any character but newline, not greedy
      [a-z]+        # 1 or more letters
      ,             # a comma
      ([^,]+)       # group 1, 1 or more non comma
      .*            # 0 or more any character but newline
      $             # end of line
    /               # replace with
      $1            # content of group 1
    /i              # case insensitive
    

    【讨论】:

      【解决方案2】:

      如果您对sed 满意,请尝试关注(根据您的描述)。

      sed 's/\([^,]*\),\([^,]*\),\([^,].*\)\(.*\)/'"'"','"'"'\3'"'"','"'"'/'  Input_file
      

      这里我使用了sed 将匹配的正则表达式值保存到内存中的能力,我们可以在替换期间使用它。

      【讨论】:

      • 是的,我会试一试
      • 是的,但它在字符串的末尾和之后添加了“','”
      • @trigster,很高兴它对您有所帮助,请找个时间给它,当您的答案很少时,您也可以从中选择任何一个答案作为正确答案,干杯。
      • 对不起,这没用,我有点仓促,它仍然在逗号之前添加了所有内容,但它确实删除了数字
      【解决方案3】:

      使用python:

          import re
          str = "000.00.000.00,000,xxx,xxx.xxx.xxx,xxx"
          matched = re.findall('.*([a-zA-Z]{3}\.[a-zA-Z]{3}\.[a-zA-Z]{3}),[a-zA-Z]{3}$',str)
          print(matched)
      

      【讨论】:

        猜你喜欢
        • 2018-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多