経度と緯度を含む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 -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
1つの方法(フィールドを明示的に繰り返すことなく)は次のようになります。
awk -F, -vOFS='],[' '
{$0 = "[" $0 "]"; $1=$1; gsub(" ",","); print}
' input.csv
しかし、IMHOでは、スペースで区切られた文字列のペアを単純に一致させ、キャプチャして次に置き換える方が簡単で自然です。sed
sed -E 's/([^,]*) ([^,]*)/\[\1,\2\]/g' input.csv