2014-07-02 32 views
2

考慮這個數據文件正則表達式來提取bash shell中引號的所有內容?

random text "txt" random text
random text "txt1" random text "txt2"
random text "txt1" random text "txt3"
random text "txt1" random text "txt4"
random text "txt1" random text "txt5"
random text "txt1" random text "txt5" random text "txt6" random text

對於每個這一行的,我需要提取的報價,即在心裏

txt
txt1,txt2
txt1,txt3
txt1,txt4
txt1,txt5
txt1,txt5,txt6
There can be multiple quotes in a single line.

我在外殼寫這個正則表達式(其實我寫了一個sed命令,但是當我在這裏貼吧,它的螺絲了。*)

^dotStar"[^"]+"dotStar$(for single number quote)
^dotStar"[^"]+"dotStar"[^"]+"dotStar$(if there are two quotes)

正如你所看到的,我的正則表達式是取決於出現的引號數量。任何人都可以給我一個通用的reg-ex,不管引用次數出現的次數,它給我的文字。

回答

5

您可以使用此sed命令:

sed --posix 's/[^"]*"\([^"]*\)"[^"]*/\1,/g;s/\(.*\),/\1/' input.txt 

輸出:

txt 
txt1,txt2 
txt1,txt3 
txt1,txt4 
txt1,txt5 
txt1,txt5,txt6 
+0

我想你可能有一個小錯誤:這對我的作品,但它是基於你的,這是非常clever: 'sed's/[^「] *」\([^「] * \)」/ \ 1,/ g; s/\(。* \),。*/\ 1 /' –

+0

那是好處嗎? – hek2mgl

+0

我把它縮小了一點。你的不適合我,但是如果你把'\ +'改成'*' –

相關問題