正则表达式匹配特定模式

时间:2014-07-31 15:53:47

标签: regex sed grep

我有

[root@centos64 ~]# cat /tmp/out
[
  "i-b7a82af5",
  "i-9d78f4df",
  "i-92ea58d0",
  "i-fa4acab8"
]

我想通过sed或grep来匹配格式“x-xxxxxxxx”,即a-z 0-9的混合总是在1- [8个字符长度]中,并省略其他所有内容

[root@centos64 ~]# cat /tmp/out| sed s/x-xxxxxxxx/
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

我知道这是基本的,但我只能找到文本替换的例子。

5 个答案:

答案 0 :(得分:1)

grep -Eo '[a-z0-9]-[a-z0-9]{8}' file

-E选项使其识别扩展的正则表达式,因此它可以使用{8}来匹配8次重复。

-o选项使其仅打印与正则表达式匹配的行的部分。

答案 1 :(得分:1)

为什么不在报价之间打印任何内容:

$ sed -n 's/[^"]*"\([^"]*\).*/\1/p' file
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

$ awk -F\" 'NF>1{print $2}' file                     
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

答案 2 :(得分:0)

通过GNU sed,

$ sed -nr 's/.*([a-z0-9]-[a-z0-9]{8}).*/\1/p' file
i-b7a82af5
i-9d78f4df
i-92ea58d0
i-fa4acab8

答案 3 :(得分:0)

我认为这就是你所需要的:[0-9a-zA-Z]-[0-9a-zA-Z]{8}。试一试here

答案 4 :(得分:0)

这应该有效^[a-z0-9]-[a-zA-Z0-9]{8}$