diff options
author | typebrook <typebrook@gmail.com> | 2019-11-17 09:18:07 +0800 |
---|---|---|
committer | typebrook <typebrook@gmail.com> | 2019-11-17 09:18:07 +0800 |
commit | 1d3508f66fddf3f8c6416e59ab9fbde405dbcf25 (patch) | |
tree | 4f703dfa01596c133a4898c88fe837b8971e47e1 /scripts/csv/csv2geojson | |
parent | e0673805fc648d47eadf5c76b822ccef5780d241 (diff) |
update
Diffstat (limited to 'scripts/csv/csv2geojson')
-rwxr-xr-x | scripts/csv/csv2geojson | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/scripts/csv/csv2geojson b/scripts/csv/csv2geojson new file mode 100755 index 0000000..085e12e --- /dev/null +++ b/scripts/csv/csv2geojson | |||
@@ -0,0 +1,43 @@ | |||
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": .}' | ||