2014-11-21 130 views
6

我目前得到的字符串,如下提取子:使用SED在大括號

[email protected]{Wed Nov 19 14:17:32 2014} branch: thebranch 

這是包含在文件中,我分析字符串。不過我想要括號內的值{Wed Nov 19 14:17:32 2014}

我對Sed沒有經驗,說實話我覺得它有點神祕。

到目前爲止,我已經設法使用以下命令,但輸出仍然是整個字符串。

我在做什麼錯?

sed -e 's/[^/{]*"\([^/}]*\).*/\1/' 

回答

3

爲了得到這是{之間的值,}

$ sed 's/^[^{]*{\([^{}]*\)}.*/\1/' file 
Wed Nov 19 14:17:32 2014 
2

這可能會實現

sed -e 's/[^{]*\({[^}]*}\).*/\1/g' 

測試

$ echo "[email protected]{Wed Nov 19 14:17:32 2014} branch: thebranch" | sed -e 's/[^{]*{\([^}]*\)}.*/\1/g' 

週三11月19日14時17分32秒2014

正則表達式

  • [^{]*比賽以外的任何其他的{,也就是說[email protected]

  • ([^}]*)捕獲組1

    • \{匹配{

    • [^}]*匹配比}其他任何東西,這就是Wed Nov 19 14:17:32 2014

    • \}匹配的}

  • .*匹配其餘

4

這是很簡單的事與awk,而不是複雜的正則表達式。

awk -F"{|}" '{print $2}' file 
Wed Nov 19 14:17:32 2014 

它設置字段分隔符{},那麼你的數據將在第二場。

FS可以設置像這樣:

awk -F"[{}]" '{print $2}' file 

要查看所有領域:

awk -F"{|}" '{print "field#1="$1"\nfield#2="$2"\nfield#3="$3}' file 
field#[email protected] 
field#2=Wed Nov 19 14:17:32 2014 
field#3= branch: thebranch 
1

簡單,下面的命令也得到了數據...

echo "[email protected]{Wed Nov 19 14:17:32 2014} branch: thebranch" | sed 's/.*{\(.*\)}.*/\1/g'