2014-12-05 50 views
1

我正在尋找最簡單的方法來替換\ n字符,但僅限於包含特定表達式的給定行。僅在包含字符串/表達式的行上使用命令行工具刪除換行符

輸入看起來像這樣

00:03:04 
text alphabetic abcde 
00:03:08 
text alphabetic abcde 
00:03:17 
text alphabetic abcde 
00:03:26 
text alphabetic abcde 

輸出會像

00:03:04 text alphabetic abcde 
00:03:08 text alphabetic abcde 
00:03:17 text alphabetic abcde 
00:03:26 text alphabetic abcde 

現在我想更換成\ n僅在非字母線。

我想最簡單的方法是'tr',但我看不出如何限制到指定的行。

我用sed擺弄,但這似乎相當成問題。

我不敢相信沒有一種優雅的方式來說 「以[0-9] [0-9]:」開頭的行代替換行符。

你會怎麼做呢?

回答

1

你有「保持緩衝」的工作:

~$ sed -r'/[0-9][0-9]:/ {N; s/ *\n/ /}' myfile 
00:03:04 text alphabetic abcde 
00:03:08 text alphabetic abcde 
00:03:17 text alphabetic abcde 
00:03:26 text alphabetic abcde 

N說:讀下一行,附加到當前一個。
然後我們做替換s/\n/ /(因爲在你的例子中你有一些空格後,你也必須刪除,因此*部分)。
並表示,只有在訂單開始/[0-9][0-9]:/

需要注意的是,如果你的文件是嚴格的形式:

time 
text 
time 
text 
... 

你不需要/[0-9]/部分:

~$ sed '{N; s/ *\n/ /}' myfile 
00:03:04 text alphabetic abcde 
00:03:08 text alphabetic abcde 
00:03:17 text alphabetic abcde 
00:03:26 text alphabetic abcde 
+1

男人,這是完美的,包括你的解釋!謝謝!我花了將近一個小時的時間,並且只用了最靈敏的sed結構。 – badlands 2014-12-05 10:44:33

0

awk應該這樣做:

awk 'ORS=NR%2?FS:RS' file 
00:03:04 text alphabetic abcde 
00:03:08 text alphabetic abcde 
00:03:17 text alphabetic abcde 
00:03:26 text alphabetic abcde 

這改變輸出記錄選擇基礎上的行數(奇數/偶數)

0

如果你想參加每對線:

paste -d " " - - < filename 
0
sed -n '/^[0-9:]*$/!{H;x;s/\n/ /;p;b};h' input 

給出:

00:03:04 text alphabetic abcde 
00:03:08 text alphabetic abcde 
00:03:17 text alphabetic abcde 
00:03:26 text alphabetic abcde 
相關問題