Skip to content

Instantly share code, notes, and snippets.

@s-leroux
Last active July 5, 2017 13:16
Show Gist options
  • Save s-leroux/de6295f26bef27a2162b27f3e97b0586 to your computer and use it in GitHub Desktop.
Save s-leroux/de6295f26bef27a2162b27f3e97b0586 to your computer and use it in GitHub Desktop.
GIS file converter from .shp to gnuplot data file
#!/bin/bash
# Original code by Hagen Wierstorf (http://www.gnuplotting.org)
# http://www.gnuplotting.org/code/shape2txt
# Shamelessly modified by Sylvain Leroux for the worst
function usage() {
echo "Usage:"
echo " shape2txt file.shp"
}
if [[ -z "$1" || ! -f "$1" ]]
then
usage >&2
exit 1
fi
INFILE="$1"
CSVFILE="${INFILE%.*}.csv"
OUTFMT="${INFILE%.*}.%s.txt"
# convert shape files to csv
rm -f "$CSVFILE"
ogr2ogr -f CSV "$CSVFILE" "$INFILE" -lco GEOMETRY=AS_WKT
# Awk script to remove , between quotes
NORMALIZE=$(cat << 'EOT'
BEGIN {
FS=")+\"";
OFS="";
}
NR==1 {
$0=("SHAPE," $0);
}
NR > 1 {
gsub(/,/,"|",$1); # Replace embedded comas
sub(/ \(+/,",",$1); # Replace (( by a coma
sub(/"/,"",$1); # Remove unneeded quotes
}
{
print
}
EOT
)
# Core processing
PROCESS=$(cat << 'EOT'
BEGIN {
FS=",";
OFS=" ";
}
NR==1 {
# Parse header
for(i = 0; i < NF; ++i)
F[$i]=i;
}
$1=="POLYGON" {
NP=1;
P[1]=$2;
}
$1=="MULTIPOLYGON" {
NP=split($2, P, /\)\)\|\(\(/);
}
NR > 1 {
CCODE=$F["sov_a3"];
CNAME=$F["sovereignt"];
FILE=sprintf(OUTFMT, CCODE);
FILES[FILE]=1; # Remember the file name
for(i = 1; i <= NP; ++i) {
sub(/\)\|\(.*/,"", P[i]); # XXX until I know how to deal with
# holes in gnuplot, just discard them
# see:
# https://stackoverflow.com/questions/44921842
# https://en.wikipedia.org/wiki/Enclave_and_exclave
NV=split(P[i], V, /\|/);
for(j = 1; j <= NV; ++j) {
print V[j], CCODE, CNAME > FILE;
}
print "" > FILE;
}
}
END {
CMD = "cat ";
for(key in FILES) {
CMD=(CMD key " ");
}
system(CMD);
}
EOT
)
awk "$NORMALIZE" "$CSVFILE" | \
awk -v OUTFMT="$OUTFMT" "$PROCESS" > $(printf "${OUTFMT}" all)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment