Linux

如何從第三個欄位列印 CSV

  • March 25, 2018

我想從第三個欄位中擷取 csv 行,直到和沒有雙引號 (")

more test

"linux02","PLD26","net2-thrift-netconf","net.driver.memory","2"
"linux02","PLD26","net2-thrift-netconf","net.executor.cores","2"
"linux02","PLD26","net2-thrift-netconf","net.executor.instances","2"
"linux02","PLD26","net2-thrift-netconf","net.executor.memory","2"
"linux02","PLD26","net2-thrift-netconf","net.sql.shuffle.partitions","141"
"linux02","PLD26","net2-thrift-netconf","net.dynamicAllocation.enabled","true"
"linux02","PLD26","net2-thrift-netconf","net.dynamicAllocation.initialExecutors","2"
"linux02","PLD26","net2-thrift-netconf","net.dynamicAllocation.minExecutors","2"
"linux02","PLD26","net2-thrift-netconf","net.dynamicAllocation.maxExecutors","20"

我試過這個

sed s'/,/ /g' test | awk '{print $3","$4","$5}' | sed s'/"//g'
,,
net2-thrift-netconf,net.driver.memory
net2-thrift-netconf,net.executor.cores
net2-thrift-netconf,net.executor.instances
net2-thrift-netconf,net.executor.memory
net2-thrift-netconf,net.sql.shuffle.partitions
net2-thrift-netconf,net.dynamicAllocation.enabled
net2-thrift-netconf,net.dynamicAllocation.initialExecutors
net2-thrift-netconf,net.dynamicAllocation.minExecutors
net2-thrift-netconf,net.dynamicAllocation.maxExecutors
,,

但我的語法有問題,因為這種語法也會列印“,”,而第二種語法並不優雅。

預期輸出:

net2-thrift-netconf,net.driver.memory,2
net2-thrift-netconf,net.executor.cores,2
net2-thrift-netconf,net.executor.instances,2
net2-thrift-netconf,net.executor.memory,2
net2-thrift-netconf,net.sql.shuffle.partitions,141
net2-thrift-netconf,net.dynamicAllocation.enabled,true
net2-thrift-netconf,net.dynamicAllocation.initialExecutors,2
net2-thrift-netconf,net.dynamicAllocation.minExecutors,2
net2-thrift-netconf,net.dynamicAllocation.maxExecutors,20

只有sed

sed -E 's/"//g; s/^([^,]*,){2}//' infile
  • s/"//g, 去掉所有雙引號。
  • ^([^,]*,){2},從行的乞求開始,刪除所有內容,後跟逗號並重複此操作最多兩次。

或與awk

awk -F\" '{$1=$2=$3=$4=$5=""}1' OFS="" infile

看起來這只是一個問題或刪除引號,然後從第三個欄位列印到行尾:

$ tr -d \" < file | cut -d, -f3-
net2-thrift-netconf,net.driver.memory,2
net2-thrift-netconf,net.executor.cores,2
net2-thrift-netconf,net.executor.instances,2
net2-thrift-netconf,net.executor.memory,2
net2-thrift-netconf,net.sql.shuffle.partitions,141
net2-thrift-netconf,net.dynamicAllocation.enabled,true
net2-thrift-netconf,net.dynamicAllocation.initialExecutors,2
net2-thrift-netconf,net.dynamicAllocation.minExecutors,2
net2-thrift-netconf,net.dynamicAllocation.maxExecutors,20

所以從第 3 個到最後一個分隔欄位tr -d \"中刪除引號和列印。cut -d, -f3-``,

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