Question

I try to append all dbfs in a folder to the first dbf. The dbfs are part of ESRI shapefiles that I want to append into one file. I got a working code but I guess what I did is really awkard (I'm an absolute bash newbie)... And as I ommit the first file my counter is counting one excessive file in the end of the loop and producing an error.. The appending is done by ogr2ogr (GDAL/OGR Library)

mydir=C:/Users/Kay/Desktop/Test_GIS/new/
cd $mydir

dbfs=(*.dbf)                                # put dir to array

let i=1                                     # start with 1 omitting 1st file with index 0

for f in *.dbf 
  do       
  echo appending file ${dbfs[i]} to ${dbfs[0]}
  ogr2ogr -append ${dbfs[0]} ${dbfs[i]}
  let i=i+1                                 # counter + 1
done
Was it helpful?

Solution

Version A: you explicitly specify to what dbf want append

append_to="fff.dbf"
find . -maxdepth 1 -name \*.dbf -print0 | grep -zv "^$append_to$" | xargs -0 -n1 -I % echo ogr2ogr -append "$append_to" "%"

Variant B: appending to the 1st dbf (1st by ls)

append_to=$(ls -1 *.dbf | head -1)
find . -maxdepth 1 -name \*.dbf -print0 | grep -zv "^$append_to$" | xargs -0 -n1 -I % echo ogr2ogr -append "$append_to" "%"

Both are now in the "dry run" mode - only shows what will do. When satisfied remove the echo from the xargs. The second line is same for both versions.

pure bash

IFS=$'\t\n'       #don't need this line when your filenames doesn't contain spaces
declare -a dbfs=(*.dbf)
unset $IFS        #don't need this line when your filenames doesn't contain spaces
append_to=${dbfs[0]}
unset dbfs[0]
for dbf in ${dbfs[@]}
do
        echo ogr2ogr -append "$append_to" "$dbf"
done

OTHER TIPS

For the record

If you use ogr2ogr for appending dbfs of shape-files, things are in fact much easier. If you pass a shp-filename that not alread exists, it creates an empty shape-file on the fly and appends the data to it. So, this will suffice:

# working directory with shp-files to be appended into one file
mydir=D:/GIS_DataBase/CorineLC/shps_extracted
cd $mydir

# directory where final shp-file will be saved
mydir_final=D:/GIS_DataBase/CorineLC/shps_app_and_extr
mkdir $mydir_final

# get dbfs, which are the actual files to which append the data to
declare -a dbfs=(*.dbf)

# loop through dbfs in dir and append all to the dbf of shp-file
# extr_and_app.shp that will be created by ogr2ogr on the fly 
# and saved to {mydir_final}
for dbf in ${dbfs[@]}; do
  echo appending $dbf to $mydir_final/extr_and_app.dbf
  ogr2ogr -append $mydir_final/extr_and_app.dbf $dbf
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top