For Loop queries

I have Existing FOR loop in script like below. But the zip should happen for only those years in another file generated dynamically.

Existing FOR LOOP -

for i in XYZ_*ABC${YEAR_2014}.csv; do
    printf "%s\n" "$i"
    done | zip -@ XYZ_2014.zip  >> $XYZ_2014.log 2>&1 || ERROR_COUNT=$((ERROR_COUNT + 1)) 
    
    
for i in XYZ_*ABC${YEAR_2015}.csv; do
    printf "%s\n" "$i"
    done | zip -@ XYZ_2015.zip  >> $XYZ_2015.log 2>&1 || ERROR_COUNT=$((ERROR_COUNT + 1)) 
    
for i in XYZ_*ABC${YEAR_2016}.csv; do
    printf "%s\n" "$i"
    done | zip -@ XYZ_2016.zip  >> $XYZ_2016.log 2>&1 || ERROR_COUNT=$((ERROR_COUNT + 1)) 

I have file which has the years for which zip should happen.

dynamic_years.txt

2014
2015

Updated version should look like below

for i in XYZ_*ABC${YEAR_2014}.csv; do
    printf "%s\n" "$i"
    done | zip -@ XYZ_2014.zip  >> $XYZ_2014.log 2>&1 || ERROR_COUNT=$((ERROR_COUNT + 1)) 
    
    
for i in XYZ_*ABC${YEAR_2015}.csv; do
    printf "%s\n" "$i"
    done | zip -@ XYZ_2015.zip  >> $XYZ_2015.log 2>&1 || ERROR_COUNT=$((ERROR_COUNT + 1)) 

It would be helpful if you can let me know how to incorporate the dynamic year change in the FOR loop.

Thanks.

Have you considered reading "dynamic_years.txt" first, in a while-loop, and applying that to the inner for-loop?

e.g.

while read YEAR; do
  for i in XYZ_*ABC$YEAR.csv; do
    printf "%s\n" "$i"
  done | zip -@ XYZ_$YEAR.zip  >> XYZ_$YEAR.log 2>&1 || ERROR_COUNT=$((ERROR_COUNT + 1))
done < dynamic_years.txt
1 Like

Is that for loop really necessary? Wouldn't

ls -1 XYZ_*ABC$YEAR.csv

do?

1 Like