diff options
Diffstat (limited to 'tools/csv2geojson')
-rwxr-xr-x | tools/csv2geojson | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/tools/csv2geojson b/tools/csv2geojson new file mode 100755 index 0000000..028aed7 --- /dev/null +++ b/tools/csv2geojson | |||
@@ -0,0 +1,46 @@ | |||
1 | #! /bin/bash | ||
2 | |||
3 | # -s to skip specify columns of longitude and latitude | ||
4 | for i in "$@" | ||
5 | do | ||
6 | case $i in | ||
7 | -s) | ||
8 | lon_col=0; lat_col=1 | ||
9 | shift;; | ||
10 | |||
11 | *) | ||
12 | csv=$i | ||
13 | shift;; | ||
14 | esac | ||
15 | done | ||
16 | |||
17 | # if no -s option, just read from input | ||
18 | if [ "$lon_col" != "0" ]; then | ||
19 | # show each field with index in csv | ||
20 | echo -------------- > /dev/tty | ||
21 | head -1 < $csv | awk -F',' '{for (i=1; i<=NF; i++) printf $i "_" i " "; print ""}' > /dev/tty | ||
22 | echo -------------- > /dev/tty | ||
23 | echo > /dev/tty | ||
24 | |||
25 | # get index of lon/lat column | ||
26 | read -p "Number of latitude column: " lat_col | ||
27 | read -p "Number of longitude column: " lon_col | ||
28 | fi | ||
29 | |||
30 | cat $csv | | ||
31 | # move lon and lat to the first and second column | ||
32 | awk -F',' -v lon_th=$lon_col -v lat_th=$lat_col '\ | ||
33 | BEGIN{OFS=","}\ | ||
34 | {printf $lon_th "," $lat_th; for (i=1; i<= NF; i++) if (i != lat_th && i != lon_th) printf "," $i; print ""}\ | ||
35 | ' |\ | ||
36 | # change csv into array format, like [lon, lat, "field1", field2...] | ||
37 | sed 's/[^,]*/"\0"/g; s/.*/[\0]/g' |\ | ||
38 | # wrap other fields as a json object, like [lon, lat, {...}] | ||
39 | jq -s '.[0][2:] as $fields | .[1:][] | [.[0], .[1], ([$fields, .[2:]] | transpose | map({(.[0]): .[1]}) | add)]' |\ | ||
40 | # create array of geojson point features | ||
41 | jq '{"type": "Feature", "properties": .[2], "geometry":{ "type": "Point", "coordinates": [(.[0] | tonumber), (.[1] | tonumber)] } }' |\ | ||
42 | # wrap features as geojson format | ||
43 | jq -s '{"type": "FeatureCollection", "features": .}' |\ | ||
44 | tee /tmp/geojson | ||
45 | |||
46 | echo stored into /tmp/geojson > /dev/tty | ||