Adding field with filename when merging shapefiles with ogr2ogr?
With small scripting it would be doable. With something like following you should be able to add column to a shapefile in all shapefiles in a folder, and merge them to merged.shp file
for %f in (*.shp) do (
ogrinfo %f -sql "ALTER TABLE %f ADD COLUMN filename character(15)"
ogrinfo %f -sql "UPDATE TABLE %f filename = '%f'"
ogr2ogr -update -append merged.shp %f -f “esri shapefile” -nln merge
)
edit: The same as a Bash script, with some changes to make it working:
for f in *.shp
do
base=${f%.shp}
ogrinfo $f -sql "ALTER TABLE $base ADD COLUMN filename character(15)"
ogrinfo $f -dialect SQLite -sql "UPDATE $base SET filename = '$base'"
ogr2ogr -update -append merged.shp $f
done
I would use the -sql option, and import the shapefile in the following way:
ogr2ogr -update -append %destination% %n2% -sql 'SELECT "%n2%" as SHAPE_ORIG, field1, field2, ... FROM %n2%'
there are some ways for merging shapefiles.
- if you want to merge layers as a one layer, you can use MMqgis tools for merging...
- if you want to merge all shapefiles under a folder, you can use DARREN COPE simple code here.
mkdir merged
for %f in (*.shp) do (
if not exist merged\merged.shp (
ogr2ogr -f “esri shapefile” merged\merged.shp %f) else (
ogr2ogr -f “esri shapefile” -update -append merged\merged.shp %f -nln Merged )
)
- beside this can use GeoMerge free tool for merging lots of file but dont forget to consider your file size for workin with it.
and adding attribute to shapefile @dango directon is good. you can use layer.CreateField(field_name) for creating a new column which is populated from
import os
shapeFileName = os.path.splitext("your_shape_file_path")[0]
i hope it helps you...