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