首页 > 解决方案 > 使用正则表达式在 a 之前和之后的文件中搜索字符串模式

问题描述

我有一个很大的日志文件,我想从该文件中获取某些信息。我正在尝试使用 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','

但没有,.

标签: regexunixgrep

解决方案


使用 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

推荐阅读