2013-05-05 82 views
5

我想知道如何僅使用sed單行程打印每個段落的第一個單詞。在這種情況下,段落由緊跟2個換行符的文本定義。僅使用sed打印每個段落的第一個詞

例如

This is a paragraph with some text. Some random text that is not really important. 

This is another paragraph with some text. 
However this sentence is still in the same paragraph. 

這應該轉化爲

This 

This 

回答

2

一種可能GNU sed的解決辦法是:

sed -rn ':a;/^ *$/{n;ba};s/(|$).*//p;:b;n;/^ *$/ba;bb' 

輸出:

This 
This 

它將僅限空格的行視爲空,並理解段落之間的任意數量的空行。也正確處理單詞段落。

7

想想 paragraph mode

 
By a special dispensation, an empty string as the value of RS indicates that 
records are separated by one or more blank lines. 

awkperl有一個「段落模式的支持,要麼會做出更好的選擇,而不是sed

awk '{ print $1 }' RS= ORS="\n\n" file 

perl -00 -lane 'print $F[0]' file 

結果:

This 

This 
+0

只是一個側面說明,如果你想將記錄分隔符被_exactly_打斷倆行,用'RS =「\ n \ n」'爲'awk'。不記得如何在cmd行的'perl'中執行它。也許其他人會知道嗎? – Steve 2013-05-05 15:13:10

+0

這麼簡單,那麼清楚.... +1當然。 – 2013-05-06 00:34:47

0

這可能會爲你工作(GNU SED):

sed ':a;$!{N;/\n\s*$/!ba};s/\s.*/\n/' file