Cartometric Blog

A scrapbook of GIS tricks, with emphasis on FOSS4G.

Terminal one-liner to create shapefile from WKT using ogr2ogr

without comments

Fair warning, this is a Linux-themed solution. But I expect, if the concepts were mirrored, it could easily be ported to a Windows solution.

Today I needed to create a shapefile with a single point geometry in it to use as an input for a random GIS utility executable, which required its input to be a an actual shapefile, as opposed to an array of coordinate pairs, or a single coordinate pair, or even separate x=/y= input parameters for a single coordinate pair. I already had the point coordinate I wanted to use, and I didn’t want to go to a lot of trouble to make this shapefile! So I got to wondering if I could use ogr2ogrto manufacture the shapefile for me.

Fortunately, with the help of some other terminal utilities available to my Ubuntu shell, I was able to come up with the following solution. This compound terminal command 1) creates an empty file (dataset.csv), 2) pushes a “feature” or features into it, and 3) uses ogr2ogr to translate the CSV into a shapefile projected accordingly–in this case, to EPSG:4326.

touch dataset.csv && printf "gid,WKT\n1,POINT(-82.048051 33.567181)\n2,POINT(-92.7774 35.9829)\n" > dataset.csv && ogr2ogr -f "ESRI Shapefile" dataset.shp -dialect sqlite -sql "SELECT gid, GeomFromText(WKT) FROM dataset" dataset.csv -a_srs EPSG:4326

Here’s a breakdown of what happens..

touch dataset.csv
- Create a file (in the current directory) named "dataset.csv"
printf "gid,WKT\n1,POINT(-82.048051 33.567181)\n2,POINT(-92.7774 35.9829)\n" > dataset.csv
- Push a string through standard output (STDOUT) and INTO (>) the new file "dataset.csv"
- The string imposes line breaks using the "\n" sequence and establishes a CSV type containing three lines
- The three lines of content include: a column header, feature 1, and feature 2
ogr2ogr -f "ESRI Shapefile" dataset.shp -dialect sqlite -sql "SELECT gid, GeomFromText(WKT) FROM dataset" dataset.csv -a_srs EPSG:4326
- The ogr2ogr command exports a shapefile, "dataset.shp"
- The input file, "dataset.csv" is included toward the end, along with the declaration of the source data's CRS (EPSG:4326/WGS84)
- ogr2ogr is instructed to use the "SQLITE" dialect of sql to pull data from the target dataset
- The SQL command makes sure ogr2ogr knows to identify the WKT column as the source data's geometry field

It runs pretty quickly, and does exactly what I wanted: Quickly crank out a shapefile if all I have is a point or a polygon or something, already in WKT format. As I’m sure I’ll be using this again, I wanted to document it here for easy reference later.

Written by elrobis

July 16th, 2020 at 5:04 pm

Leave a Reply