簡體   English   中英

正則表達式匹配特定模式

[英]regex match specific pattern

我有

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

我想通過sed或grep傳遞管道以匹配格式“ x-xxxxxxxx”,即始終以1- [8個字符長度]混合az 0-9,並省略其他所有內容

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

我知道這是基本的,但是我只能找到文本替換的示例。

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

-E選項可以識別擴展的正則表達式,因此可以使用{8}來匹配8個重復。

-o選項使它僅打印與正則表達式匹配的行的一部分。

為什么不只打印引號之間的內容:

$ 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

通過GNU sed,

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

我認為這就是您所需要的: [0-9a-zA-Z]-[0-9a-zA-Z]{8} 在這里嘗試。

這應該可以工作^[a-z0-9]-[a-zA-Z0-9]{8}$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM