[英]how to sed spacial character if it come inside double quote in linux file
我有一個用逗號 (,) 分隔的 txt 文件,每列用雙引號引用
我想要做的是:我需要將分隔符保留為逗號,但我想刪除每個逗號進入雙引號(因為每列都用雙引號引起來)
輸入示例和我想要的 output 文件
輸入文件:
"2022111812160156601777153","","","false","test1",**"here the , issue , that comma comma come inside the column"**
我想要的 output:
"2022111812160156601777153","","","false","test1",**"here the issue that comma comma come inside the column"**
我嘗試的是:
sed -i ':a' -e 's/\("[^"]*\),\([^"]*"\)/\1~\2/;ta' test.txt
但上面的 sed 命令不僅替換了列內的逗號,還替換了所有逗號
有辦法嗎?
使用sed
$ sed -Ei.bak ':a;s/((^|,)(\*+)?"[^"]*),/\1/;ta' input_file
"2022111812160156601777153","","","false","test1",**"here the issue that comma comma come inside the column"**
任何時候你發現自己在 sed 中使用的不僅僅是s
、 g
和p
(帶-n
),你最好還是使用 awk 以獲得清晰度、健壯性、效率、可移植性等的某種組合。
在每個 Unix 框上的任何 shell 中使用任何 awk:
$ awk 'BEGIN{FS=OFS="\""} {for (i=2; i<=NF; i+=2) gsub(/,/,"",$i)} 1' file
"2022111812160156601777153","","","false","test1",**"here the issue that comma comma come inside the column"**
就像 GNU sed 在您的問題中有-i
使用命令的 output 更新輸入文件一樣,GNU awk 有-i inplace
inplace ,或者只是添加> tmp && mv tmp file
與任何 awk 或任何其他 Unix 命令。
這可能對你有用(GNU sed):
sed -E ':a;s/^(("[^",]*"\**,?\**)*"[^",]*),/\1/;ta' file
這遍歷每一行,刪除成對的雙引號字段中的任何逗號。
注意上面的解決方案也適用於以零或*
為前綴/后綴的雙引號字段。 如果不應該滿足這一點,這里有一個改進的解決方案:
sed -E ':a;s/^(("[^",]*",?)*"[^",]*),/\1/;ta' file
NB 轉義雙引號和逗號需要一個或多個涉及的正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.