一千萬個為什麽

搜索

從stdout中刪除行尾字符?將多條線條合並成一條線

我有一個腳本輸出以下文本。這是來自 Netopia 2210-02 ADSL2 調制解調器。 ADSL Line State: Up ADSL Startup Attempts: 1 ADSL Modulation: DMT ADSL Data Path: Fast Datapump Version: DSP 7.2.3.0, HAL 7.2.1.0 SNR Margin: 8.20 9.00 dB Line Attenuation: 57.50 31.00 dB Output Power: 17.09 12.34 dBm Errored Seconds: 0 0 Loss of Signal: 0 476 Loss of Frame: 0 0 CRC Errors: 57921 416 Data Rate: 2880 1024

我怎樣才能刪除每行的結束字符?我希望輸出看起來像這樣(是的,它很醜): ADSL Line State: Up ADSL Startup Attempts: 1 ADSL Modulation: DMT ADSL Data Path: Fast Datapump Version: DSP 7.2.3.0, HAL 7.2.1.0 SNR Margin: 8.20 9.00 dB Line Attenuation: 57.50 31.00 dB Output Power: 17.09 12.34 dBm Errored Seconds: 0 0 Loss of Signal: 0 476 Loss of Frame: 0 0 CRC Errors: 57921 416 Data Rate: 2880 1024

我嘗試了一些這樣的解決方案,但他們不工作:

(This simply outputs the contents of the script, unmodified)

[email protected]:~/Work/Cacti $ ./script | sed -e 's/$//'

我也試過使用 tr 。我期待以下命令用空格字符替換每個換行符。這將采用多條線並將它們組合成一條長單線。相反,這只顯示最後一行輸出。它似乎用下一行輸出覆蓋每個後續行。 [email protected]:~/Work/Cacti $ ./script | tr '\n' ' ' Data Rate: 2880 [email protected]:~/Work/Cacti $ [email protected]:~/Work/Cacti $

Update: 經過進一步檢查,看起來每行都有一個返回字符。當使用 less 時,這顯示為 ^ M 。所以,我添加了兩個 tr 語句。一個刪除換行符,一個刪除換行符。 ./script | | tr -d '\n' | tr -d '\r'

最佳答案

sed won't work (easily) because it operates on lines one at a time; you could do it, but it would involve copying the whole input into the hold buffer tr actually should work the way you pasted it; are you sure the newlines are \ns? You can simplify it a bit by deleting the newlines instead of converting them to spaces: tr -d '\n'

轉載註明原文: 從stdout中刪除行尾字符?將多條線條合並成一條線