我有一个 CSV 文件,其中包含经度和纬度:
输入.csv
103.771 1.44849,103.771 1.44894,103.771 1.4489,103.772 1.44802,103.772 1.4479,103.774 1.44948,103.775 1.4501,103.778 1.4512,103.78 1.45145,103.781 1.45151,103.783 1.45118,103.786 1.45035,103.787 1.45007,103.789 1.4492,103.79 1.44898,103.791 1.44918,103.793 1.4498,103.793 1.44984,103.794 1.44939,103.795 1.44816,103.797 1.44214,103.798 1.44095,103.797 1.44036,103.796 1.43938,103.793 1.4383,103.793 1.43779,103.791 1.43624,103.79 1.43503,103.789 1.43341,103.788 1.43235,103.788 1.43208,103.788 1.43161,103.787 1.4299,103.787 1.42869,103.788 1.42771,103.789 1.42693,103.79 1.42592,103.79 1.42401,103.79 1.42279,103.79 1.42149,103.789 1.41974,103.789 1.41716,103.788 1.4146,103.788 1.41244,103.787 1.41201,103.786 1.41175,103.785 1.41141,103.784 1.41095,103.783 1.41079,103.782 1.41072,103.78 1.41074,103.78 1.41074,103.778 1.41071,103.776 1.41079,103.775 1.41056,103.773 1.41008,103.772 1.4101,103.771 1.42498,103.772 1.43239,103.772 1.43484,103.772 1.43566,103.771 1.44849
我想在每个坐标集之间添加括号和逗号,结果如下
输出.csv
[103.771,1.44849],[103.771,1.44894],[103.771,1.4489],[103.772,1.44802],[103.772,1.4479],[103.774,1.44948],[103.775,1.4501],[103.778,1.4512],[103.78,1.45145],[103.781,1.45151],[103.783,1.45118],[103.786,1.45035],[103.787,1.45007],[103.789,1.4492],[103.79,1.44898],[103.791,1.44918],[103.793,1.4498],[103.793,1.44984],[103.794,1.44939],[103.795,1.44816],[103.797,1.44214],[103.798,1.44095],[103.797,1.44036],[103.796,1.43938],[103.793,1.4383],[103.793,1.43779],[103.791,1.43624],[103.79,1.43503],[103.789,1.43341],[103.788,1.43235],[103.788,1.43208],[103.788,1.43161],[103.787,1.4299],[103.787,1.42869],[103.788,1.42771],[103.789,1.42693],[103.79,1.42592],[103.79,1.42401],[103.79,1.42279],[103.79,1.42149],[103.789,1.41974],[103.789,1.41716],[103.788,1.4146],[103.788,1.41244],[103.787,1.41201],[103.786,1.41175],[103.785,1.41141],[103.784,1.41095],[103.783,1.41079],[103.782,1.41072],[103.78,1.41074],[103.78,1.41074],[103.778,1.41071],[103.776,1.41079],[103.775,1.41056],[103.773,1.41008],[103.772,1.4101],[103.771,1.42498],[103.772,1.43239],[103.772,1.43484],[103.772,1.43566],[103.771,1.44849]
我怎样才能在 Linux 中做到这一点?
答案1
sed "s#,#],[#g;s# #,#g;s#^#[#;s,$,]," input > output
awk解决方案
awk -F, '{
for(i=1;i<=NF;i++)
{
sub(" ",",",$i);
i==NF?out=O $i C:out=O $i C",";
printf("%s",out)
}
}' O="[" C="]" input > output
awk '{gsub(",","],["); sub(/^/,"["); sub(/$/,"]"); sub(" ",",")}1' input > output
答案2
我可能会尝试:
cat infile | sed 's/,/\],\[/g
s/ /,/g
s/^/\[/
s/$/\]/' > outfile
答案3
由于您标记了您的问题awk
,因此一种方法(无需显式循环字段)是
awk -F, -vOFS='],[' '
{$0 = "[" $0 "]"; $1=$1; gsub(" ",","); print}
' input.csv
然而,恕我直言,简单地匹配和捕获空格分隔的字符串对并将它们重新替换为更简单、更自然sed
sed -E 's/([^,]*) ([^,]*)/\[\1,\2\]/g' input.csv