2013-10-18 29 views
2

我試圖用\s來指定,而空格grep正則表達式,但似乎grep無法識別它。 grep -Eegrep也沒有與它一起工作。在grep中支持正則表達式轉義序列

這裏是我的考驗:

$ echo ' foo' | grep '^ *foo' 
    foo 
$ echo ' foo' | grep '^\s*foo' <-- **No Output** 
$ echo ' foo' | grep -E '^\s*foo' <-- **No Output** 
$ echo ' foo' | egrep '^\s*foo' <-- **No Output** 
$ echo ' foo' | grep '^[[:space:]]*foo' 
    foo 

我也注意到,它承認\w但不\d

闕1.是否有可能使grep識別\s

闕2.我在哪裏可以找到支持grep的正則表達式轉義序列的列表?

OSRHEL5

殼牌:嘗試shbashtcsh

$ grep --version 
grep (GNU grep) 2.5.1 

編輯

我試着用grep -P作爲答案的建議,但遺憾的是它沒有牛逼的工作對我的系統拋出以下錯誤:

$ echo ' foo' | grep -P '^\s*foo' 
grep: The -P option is not supported <-- **ERROR** 
+0

僅供參考......在Perl的grep()接受\ S。我已經在PERL中嘗試了下面的程序,它工作正常。'我的@Arr =(「Test」,「Test」); @Arr = grep {$ _ =〜/^\ s + Test /} @Arr; print「@Arr」; '輸出:「測試」 – Anand

+0

@Anand是的。我注意到PERL中的grep工作正常。我的意圖是讓它在linux shell上工作 – jkshah

回答

2

沒有grep的egrep的或不承認\s\d(PCRE特定的結構),因爲它使用ERE。如果你使用grep -P那麼所有PCRE功能被認爲

POSIX and ERE Regex

雖然:請參閱本參考指南。

例如

echo ' foo' | grep -P '^\s*foo' 
    foo 
+0

不幸的是'-P'選項在我的系統上不起作用。 'grep:-P選項不支持' – jkshah

+0

已更新的操作系統和shell問題試過 – jkshah

+0

@jkshah:我確定你可以在RHEL上通過RPM獲得gnu grep – anubhava

2

Que 1. Is it possible to make grep recognize \s ?

使用Perl的正則表達式模式:

echo ' foo' | grep -P '^\s*foo' 

Que 2. Where do I find a list supported regex escape sequences in grep ?

man grep 

有它說,例如:

The symbols \< and > respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [[:alnum:]] and \W is a synonym for [^[:alnum:]].

沒有其他[A-ZA-Z]被提及

版本:

grep (GNU grep) 2.14 

在Debian

+0

不幸的是-P選項在我的系統上無法正常工作。 grep:-P選項不受支持。更新的問題 – jkshah