Home > OS >  looping into files having same string in second part of its name
looping into files having same string in second part of its name

Time:12-03

I am using loop instruction to zip many csv file based in their prefix (first element of its name)

 printf '%s\n' *_*.csv | cut -d_ -f1 | uniq |
    while read -r prefix
    do
      zip $ZIP_PATH/"$prefix"_"$DATE_EXPORT"_M2.zip "$prefix"_*.csv
    done

And it works very well, as an input I have

123_20211124_DONG.csv
123_20211124_FINA.csv
123_20211124_INDEM.csv
123_20211202_FINA.csv
123_20211202_INDEM.csv

and the zip loop will pack all these files because they have the same prefix Or, I would like to pack only those which has $DATE_EXPORT= 20211202, in other word, I want to pack only those which has second element in file name=20211202 == DATE_EXPORT variable I tried using grep function like :

 printf '%s\n' *_*.csv | grep $DATE_EXPORT | cut -d_ -f1 | uniq |
    while read -r prefix
    do
      zip $ZIP_PATH/"$prefix"_"$DATE_EXPORT"_M2.zip "$prefix"_*.csv
    done

But, does not work, any help, please ?

CodePudding user response:

"$prefix"_*.csv in the zip command in your second example is not filtered for "$DATE_EXPORT". Try "${prefix}_${DATE_EXPORT}_"*.csv or similar. You can also use *"_${DATE_EXPORT}_"*.csv with printf, instead of grep.

Also, I'm not sure what's going on with $cut, but obviously cut is the usual name.

  • Related