![](/img/trans.png)
[英]ubuntu linux shell scripting with command line grep and split delimiter
[英]Linux Shell - Grep command
我在使用grep時遇到問題: \\{n\\}
, \\{n,\\}
和\\{n,m\\}
。 我有一個名為“new”的文件,其中包含以下行:
aaaa
aaa
aa
a
當我使用grep 'a\\{1\\}' new
我得到這個輸出:
aaaa
aaa
aa
a
所以,基本上,這個命令會顯示包含1個或更多連續出現的字符“a”的行嗎?
另外, grep 'a\\{1,\\} new
會和grep 'a\\{1\\}' new
做同樣的事情嗎? 因為我得到兩個相同的輸出。
最后一個, \\{n,m\\}
,我真的不明白它的作用。
如果有人能幫助我,我真的很感激。
grep 'a\\{n,m\\}' new
表示從new中獲取至少n個a
和最多m個a
。
例如, grep 'a\\{2,3\\}' new
將輸出
aaaa
aaa
aa
最后一行不匹配,因為它只有a
。
對於a{n,\\}'
,省略m
表示任何大於或等於n
。
從man grep
:
Repetition
A regular expression may be followed by one of several repetition
operators:
? The preceding item is optional and matched at most once.
* The preceding item will be matched zero or more times.
+ The preceding item will be matched one or more times.
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
{n,m} The preceding item is matched at least n times, but not more
than m times.
那個例子grep 'a\\{2,3\\}' new
匹配了aaaa
的行,因為前三個(或2) a
。 其余部分並不重要。
如果你想要只匹配2或3個連續的a
,你可以使用-o
標志。 但請注意,這將從aaaaa
的一行輸出aa
和aaa
。 為避免這種情況,您必須使用其他信息,例如示例換行符^
和$
。
順便說一句。 我建議使用-E
標志(或egrep
是相同的),因此你有擴展的正則表達式支持。 您不必轉義括號。
用於輸入
aaaaa
aaaa
aaa
aa
a
grep -o -E '^a{2,3}$'
的調用將給出輸出:
aaa
aa
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.