2011-12-10 88 views
2

我輸入線:追加線用Perl

Movies: Action 
Adventure 
Biography 
Comedy 
Books: 
Biography 
Romance 
Sci-Fi 
War 

我的問題(在Perl中實現):檢查內容的行類似,如果結尾「:」下一行追加到它。

在我的示例中,它將包含「Books:」的行連接到包含「Biography」的行,但這只是一個示例 - 行的內容可能在很多方面有所不同。

Movies: Action 
Adventure 
Biography 
Comedy 
Books: Biography 
Romance 
Sci-Fi 
War 

回答

0

可以使用後視聲明:

s/(?<=:)\s*\n/ /gs; 
+1

+1,尼斯方法。不知道爲什麼你有一個downvote雖然。 – sidyll

+0

* [sidyll](http://stackoverflow.com/users/557306/sidyll)*:謝謝。我也不知道。 :-) –

+0

-1是多餘使用** s **標誌的。 – Sorin

0

你可以這樣做:

perl -pe 's/\r?\n$//if(/:\s*$/)' file 

perl -pe 'chomp if(/:\s*$/)' file 

如果你是好與:後沒有空格。

0

這裏一個小程序在您輸入的工作:

while (<>) { 
    s/\s+$//if /:$/; 
    print; 
} 

由於結構是完全-p選項提供什麼,你可以從你的shell做在一個行:

perl -pe 's/\s*//if /:$/' text_file 
0

類似$text =~ s/:\s*\n/: /msg;