如何在文件中的換行符欄位值中新增引號

如何在文件中的換行符欄位值中新增引號

輸入檔案具有兩個記錄和三個字段,第二個屬性包含換行符。

輸入檔:

100|Alert created becuase of high volume.
Money withdrawan more 5000.
Try to access acccount from unathorised devíce|2019-01-24
200|Minimum amount not avialable in your account.
Last time deposited amonut month ago|2019-01-24

所需的輸出應如下所示

"100"|"Alert created becuase of high volume.
Money withdrawan more 5000.
Try to access acccount from unathorised devíce"|"2019-01-24"
"200"|"Minimum amount not avialable in your account.
Last time deposited amonut month ago"|"2019-01-24"

答案1

你可以嘗試使用這個 awk :

awk -F'\n' '!f{$1="\""$1;f=1}{f=f+gsub("[|]","\"|\"")}f==3{$0=$0"\"";f=0}1' infile

答案2

你可以這樣做perl

perl -0pe 's/([^|]*)\|([^|]*)\|([^|\n]*)(\n|$)/"\1"|"\2"|"\3"\4/g' input_file
  • -0一次讀取文件,而不是逐行讀取。
  • -p列印最後一行
  • -e表達方式
  • s/pattern/replacement/g用替換替換圖案

答案3

$ cat input.txt | tr "\n" "\t" \
  |awk -v FS="|" -v OFS="|" '{for(i=1;i<=NF;i++) $i="\""$i"\"";}1' \
  |tr "\t" "\n"
  • tr將新行轉換為選項卡。所以輸入是線性化的
  • 我們告訴awk將 處理|為字段分隔符號。現在我們可以迭代每個欄位並添加引號。然後列印整行
  • tr將製表符轉換回新行

相關內容