Linux

如何從文件中刪除雙引號但不在雙引號內

  • August 22, 2017

我們有部分 CSV 文件的範例(只有 3 個欄位)

我們的目標是刪除所有"字元,但不在雙引號內

ssl-server,"ssl.server.truststore.type","jks"
tez-env,"enable_heap_"\n"dump","false"
tez-env,"heap_dump_location"\n"port","/tmp"
tez-env,"tez_user","tez"

預期輸出:

ssl-server,ssl.server.truststore.type,jks
tez-env,enable_heap_"\n"dump,false
tez-env,heap_dump_location"\n"port,/tmp
tez-env,tez_user,tez

我建議使用專用軟體進行 csv 操作,儘管sed如果雙引號內沒有逗號,這種情況可以很簡單地解決:

sed 's/^"//;s/",/,/g;s/,"/,/g;s/"$//' file

sed解決方案:

sed 's/^"\|"$//g; s/"*,"*/,/g;' file

awk方法:

awk -F, '{ for(i=1;i<=NF;i++) gsub(/^"|"$/,"",$i) }1' OFS=',' file

輸出(兩種方法):

ssl-server,ssl.server.truststore.type,jks
tez-env,enable_heap_"\n"dump,false
tez-env,heap_dump_location"\n"port,/tmp
tez-env,tez_user,tez

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