2016-07-31 36 views
1

我使用Ubuntu 14.04,和我有下面的語句:sed的 - 正則表達式的方括號檢測的Linux

192.168.2.4 [text to capture] Test: This is a test statement. 

我試圖捕捉到「文本捕獲」使用下面的正則表達式:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^\[\]]*\[(.*)\].*$/\1/" 

正則表達式的思想是遍歷所有不匹配開合方括號的字符。遇到方括號時,捕獲文本直到遇到右括號,然後忽略所有後續字符。

當我在regex tester中使用上述正則表達式時,我可以看到「正在捕獲的文本」正在被捕獲。

然而,執行上述正則表達式的命令又名返回完整的語句:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^\[\]]*\[(.*)\].*$/\1/" 

任何人能發現我在這裏錯過了什麼?我相信我已經正確地脫離了字符括號,因爲它與正則表達式測試程序正常工作。

感謝 約翰

回答

2

實際上,你只需要排除在第一條語句開始[

echo "192.168.2.4 [text to capture] Test: This is a test statement" | sed -r "s/^[^[]*\[(.*)\].*$/\1/" 

如果你真的想要一個[^ ]內都[]只使用[^][]和你不不需要逃跑。

4

你可以使用這個sed的:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
sed -r 's/^[^[]*\[([^]]*)\].*$/\1/' 

text to capture 

但是爲了簡單起見,我建議使用awk來避免複雜的正則表達式:

echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
awk -F '[][]' '{print $2}' 

text to capture 

這裏是一個gnu grep替代爲相同的(雖然AWK推薦):

echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
grep -oP '[^][]+(?=\])' 

text to capture 
2
$ echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
sed -E 's/.*\[([^]]*)\].*/\1/' 
text to capture 

如果您使用GNU-SID,注意使用無證-E選項,使擴展正則表達式

1
$ echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
    sed -E 's/.*\[([^]]+).*/\1/' 
text to capture 

$ echo "192.168.2.4 [text to capture] Test: This is a test statement" | 
    sed -E 's/.*\[(.*)\].*/\1/' 
text to capture 
0

這是使用「剪切」命令,來提取括號內的文字的另一種方法在Linux中。第一個「剪切」提取在第一個方形(開頭)括號之後出現的文本,而第二個剪切從第一個剪切語句的輸出中提取在方形括號之前出現的文本。

echo "192.168.2.4 [text to capture] Test: This is a test statement" | cut -d"[" -f2 | cut -d"]" -f1 
text to capture 

感謝

約翰

+1

你能添加說明?就目前情況而言,目前還不清楚這是什麼(它是否打算作爲對問題的更新?)或者它的作用。 – Laurel