簡體   English   中英

sed - 替換后面跟不是5位數的換行符

[英]sed - Replace new line characters not followed by 5-digit number

我有一個帶有一些(臟)數據庫架構的csv文件。

例:

10391,0,3,4,12,44 --ok
10391,0,3,4,      --not ok
12,44             --not ok
10391,0,3,4,12,44 --ok

我想寫sed腳本來替換帶有空格的新行字符(后面跟不是5位數字)。

寫了這個,但對我來說不正常:

sed 's/\n\([0-9]{1,4}\)/ \1/g' 

在這個樣本上運行

11111 sss
22222 aaa
3333 aaa
333 sss
22 sss
1 sss

應該產生

11111 sss
22222 aaa 3333 aaa 333 sss 22 sss 1 sss

感謝任何能夠提供幫助的人

或者使用Perl One-Liner

perl -0777 -pe 's/\n(?!\d{5}\b)/ /g' yourfile

說明

  • \\n匹配換行符
  • (?!\\d{5}\\b)斷言后面的內容不是五位數和一個字邊界
  • 我們插入一個空格

使用awk

awk -v ORS= 'NR > 1 { printf /^[0-9]{5} / ? "\n" : " " } 1
    END { if (NR) printf "\n" }' file

輸出:

11111 sss
22222 aaa 3333 aaa 333 sss 22 sss 1 sss
awk '{printf "%s%s" ,(NR>1&&$0~/^[0-9]{5} /?"\n":" "),$0}END{print ""}'

應該適用於你的例子:

kent$  echo "11111 sss
22222 aaa
3333 aaa
333 sss
22 sss
1 sss"|awk '{printf "%s%s" ,(NR>1&&$0~/^[0-9]{5} /?"\n":" "),$0}END{print ""}'
11111 sss
22222 aaa 3333 aaa 333 sss 22 sss 1 sss

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM