diff options
| author | Hsieh Chin Fan <pham@topo.tw> | 2023-02-14 13:33:23 +0800 |
|---|---|---|
| committer | Hsieh Chin Fan <pham@topo.tw> | 2023-02-14 13:33:23 +0800 |
| commit | 6fae25b305d714b3ab7608fa003f1af9bf024545 (patch) | |
| tree | 05507b2c0505659d2fd847ecce988dacab63a236 /bin/csv/csv.2geojson | |
| parent | 41ad31a2dee9ff912f222652f022b4c55cddcbf7 (diff) | |
Rename tools into bin
Diffstat (limited to 'bin/csv/csv.2geojson')
| -rwxr-xr-x | bin/csv/csv.2geojson | 46 |
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 | ||
| 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 | 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 | ||
| 28 | fi | ||
| 29 | |||
| 30 | (which dos2unix &>/dev/null && dos2unix <$csv || 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 | ||