Question

I have a series of zipped files with standardized names (file1pop.zip, ..., filenpop.zip). Inside each of these files, I have a file of interest popdnamei.asc, with i={1,n}. I want to execute two commands on these files (among which converting the asc files to tif). However, I can't get my bash script to work. I think I am not understanding correctly how to chop strings on bash. Does anybody know which is my mistake?

################### 
##  Choose path
###################
cd 
cd path/to/my/directory/with/zipfiles

###################
##  Unzip, convert to tif and project (WGS84)
###################

for x in *pop.zip
do
echo $x
files=${x%%.*}  #with this I hope to target the base name "filei", i={1,n} without the ".zip" extension
mkdir $files
    unzip -d $files  $x
y=popd*.asc  
if [ -f $files/$y ]  #with this I want to run my commands only if the file popdnamei.asc does exist in the file
then
        newy=${y%%.*}   #extract "popdnamei" without ".asc" extension
        gdal_translate $files/$y $files/$newy.tif  #command 1
        gdalwarp -s_srs "WGS84" -t_srs "WGS84" $files/$newy.tif $files/$newy_PROJ.tif  #command 2
        cp $files/$newy_PROJ.tif ../Output_Storage/ 
fi
rm -rf $files
done    

I think I have a problem with variable $y. I checked while the program was running and the output files are literally named "newypopd*.tif" with the asterisk instead of being named with the "completed" name (popdnamei.tif). Moreover no file is written to my Output_Storage directory. I think I have a trouble chopping a variable defined with an asterisk for completion, and I am not fully understanding what it is. Can somebody help me? Thank you.

Was it helpful?

Solution

The problem is with the statement

 y=pop*.asc

The bash filename expansion features tries to find matches for the given filename pattern. If no matches found, the pattern provided is assigned to the variable. In your case, the unzipped pop*.asc file are within the subfolder $files, so no matches are found and pattern itself is assigned to the variable 'y'.

I suggest to have another inner-loop to iterate over unzipped files.

for y in $files/pop*.asc; 
do
        if [ -f $y ]
        then 
            newy=${y%%.*}   #extract "popdnamei" without ".asc" extension
            gdal_translate $y $newy.tif  #command 1
            gdalwarp -s_srs "WGS84" -t_srs "WGS84" $newy.tif $newy_PROJ.tif  #command 2
            cp $newy_PROJ.tif ../Output_Storage/ 
        fi
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top