[英]Regex to find N (specified number) words before and after a specific word
[英]How to find string before and after specified word using Grep and RegEx
例如,我有一個包含ff組字符串的文件
AAA1111BBB -> FILE1
AAA2222BBB -> FILE2
AAA3333BBB -> FILE3
現在,在Unix中,我想通過搜索AAA模式作為行的開頭並搜索BBB作為模式的結尾來提取所有ID。 輸出將是這樣的
1111
2222
3333
然后,我要刪除所有重復的條目,然后將其保存在文件中。 我該怎么做?
如果您有grep -P
選項可用,可以嘗試
(?<=A{3})\d+(?=B{3})
此正則表達式使用環顧四周來查找由AAA
和BBB
包圍的數字
好吧,您的小示例可以通過以下命令完成:
sed -e 's/^AAA//' -e 's/BBB.*//' input.txt | sort -u > output.txt
但是,我的猜測是,您的玩具示例可能無法充分說明您要完成的工作...
使用GNU awk:
gawk '
match($1, /^AAA(.*)BBB$/, m) {keys[m[1]]=1}
END {for (k in keys) print k}
' file
或perl
perl -nE '/^AAA(\w+)BBB/ and $k{$1}=1 }END{ say join "\n", keys %k' file
我假設您的ID是4位數字:
grep -oE "AAA[0-9]{4}BBB" <filename> | grep -oE "[0-9]{4}"
編輯:
如果您有類似“ AAA12 @ 3BBB”的字樣:
grep -oE "AAA.{4}BBB" <filename> | grep -oE "[0-9,@]{4}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.