Shell

Perl 兩種模式之間的多行數據成一行輸出

  • July 2, 2020

文件 1

pure info:       myjob-relaed_rawmaterila
Timings:              Full
pure info:       Check-platform-Log-90Days
Timings:              Full
Timings:              Incremental
pure info:       Check-vitorydows-Log-90Days
Timings:              Full
Timings:              Incremental
pure info:       Note_michael
Timings:              Full
pure info:       adhoc-activity-myjob-platform
Timings:              Full
pure info:       adhoc-activity-myjob-vitory
Timings:              Full
pure info:       adhoc-myjob-platform-03
Timings:              Full
Timings:              Full-1month
pure info:       adhoc-onetime-myjob-hotcase
Timings:              Full
pure info:       adhoc-onetime-myjob-platform

需要輸出

pure info: myjob-relaed_rawmaterila Timings:  Full
pure info: Check-platform-Log-90Days Timings:  Full Timings:  Incremental
pure info: Check-vitorydows-Log-90Days Timings:  Full Timings:  Incremental
pure info: Note_michael Timings:  Full
pure info: adhoc-activity-myjob-platform Timings:  Full
pure info: adhoc-activity-myjob-vitory Timings:  Full
pure info: adhoc-myjob-platform-03 Timings:  Full Timings:  Full-1month
pure info: adhoc-onetime-myjob-hotcase Timings:  Full

我試過了

cat file1|sed -e 's/^ //' -e 's/$// 
cat file1|perl -pe's/\n/ / if $.  % 3' 

但這僅在一行中列印 2 行,如果有額外的Timings條目,那麼這就是鋸齒形輸出。

我怎麼解決這個問題?

關於您的 perl 解決方案:由於 -p 構造,提供的腳本逐行處理輸入。這使得連接線變得困難,因為線不知道接下來會發生什麼。

當您將輸入作為一個字元串處理時,您可以執行智能替換來連接行。這是一個類似於您呼叫 perl 的方式的範例:

perl -e 'local $/;my $data = <>; $data =~ s/\nTiming/ Timing/g ; print $data' file1

此腳本讀取一個字元串 ($data) 中的整個輸入,並將 Timing 之前的換行符替換為空格。它適用於所有情況(替換後g切換為全域)

GNU sed 解決方案:

sed -rz 's/\n(Timings)/ \1/g' file1

引用自:https://unix.stackexchange.com/questions/596022