3

我正在研究 bash 脚本。

var=$(ls -t1 | head -n1);
cat $var | sed 's/"//g' > latest.csv
cat latest.csv | sed -e 's/^\|$/"/g' -e 's/,/","/g' > from_epos.csv
echo "LATEST: $var";

这是整个脚本,它的意思是从当前文件中删除所有引号并在每个字段之间添加新引号。

输入:

"sku","item","price","qty"
5135,"ITEM1",1.79,5
5338,"ITEM2",1.39,5
5318,"ITEM3",1.09,5
5235,"ITEM4",1.09,5
9706,"ITEM5",1.99,5

输出:

"sku","item","price","qty"
"5135","ITEM1","1.79","5
"
"5338","ITEM2","1.39","5
"
"5318","ITEM3","1.09","5
"
"5235","ITEM4","1.09","5
"
"9706","ITEM5","1.09","5
"

我的理想输出是:

"sku","item","price","qty"
"5135","ITEM1","1.79","5"
"5338","ITEM2","1.39","5"
"5318","ITEM3","1.09","5"
"5235","ITEM4","1.09","5"
"9706","ITEM5","1.99","5"

似乎它在当前输出中的行之间输入随机字符,例如“,引号在 CR 和 LF 之间。

有什么问题以及如何使其达到我的理想愿景?

谢谢,

亚当

4

3 回答 3

4
awk 'BEGIN{FS=OFS=","}{gsub(/\"/,"");gsub(/[^,]+/,"\"&\"")}1' input
于 2013-06-18T18:45:39.793 回答
2

使用 sed 的解决方案:

sed -e 's/"//g; s/,/","/g; s/^/"/; s/$/"/'

长管道评论版本:

sed -e 's/"//g' | # removes all quotations
sed -e 's/,/","/g' | # changes all colons to ","
sed -e 's/^/"/; s/$/"/' # puts quotations in the start and end of each line
于 2013-06-18T19:02:35.920 回答
1

awk 可以在一个命令中完成所有这些操作:

awk -F"," 'NR>1{for(i=1; i<=NF; i++) {if (!($i ~ /^"/)) printf("\"%s\"",$i); 
           else printf("%s",$i); if (i<NF) printf(","); else print "";}}' latest.csv

编辑:

试试这个 awk:(根据 JS 建议的命令修改)

awk 'BEGIN{FS=OFS=","}{gsub(/\"/,"");gsub(/[^,\r]+/,"\"&\"")}1' 

或者

awk -F"[,\r]" 'NR==1{print} NR>1{for(i=1; i<NF; i++) {if (!($i ~ /^"/)) 
               printf("\"%s\"",$i); else printf("%s",$i); if (i<NF-1) printf(",");
               else print "";}}'
于 2013-06-18T18:49:29.457 回答