0

I have a script that processes files based on drop folders, I created a function to do the processing and based on a set of variables I process a folder

funtion filedetect {
//
<some processing code code>
//
}

folder=1
source="/dir_1/"
reciep="[email protected]"
filedetect    

folder=2
source="/dir_2"
reciep="[email protected]"
filedetect

Now I would like to add a piece of code to create 1 text file with a counter that basically counts how many files are found and processed in each folder. That is why I added the variable 'folder' so that the text file contains something like:

FOLDER 1 = [count]
FOLDER 2 = [count]
etc.

But for that I need to read by line the previous 'count' and replace that with count=count+1

How do I read the correct line based on the text file?

2 Answers 2

2

Assuming you've started with something like this

folder1=10
folder2=4
folder3=7

You can write it out with a command such as this

set | grep -E '^folder[0-9]+=' > counter.txt

To read it back in again you can simply source the file

source counter.txt

If you have a shell that handles arrays (bash, zsh) you can index the set of folders to an arbitrarily large number

folder[1]=10
folder[2]=4
folder[3]=7

And write this one variable array out with

set | grep '^folder=' > counter.txt

Read it back in using source, as above.

For arrays you would reference them like this echo "${folder[1]}" or foreach f "${folder[@]}"; do ... done. Or even this if your index values are in strict ascending order from 1:

i=1
while [[ $i -le ${#folder[*]} ]]
do
    echo "$i => ${folder[$i]}"
    ((i++))
done
1
  • This I will try to add into the script. Dec 10, 2018 at 9:45
0

Assuming you have a file in YAML format, like

folder1: 10
folder2: 20
folder3: 30

You may use yq from https://kislyuk.github.io/yq/ to increment the count associated with folder n by one using

yq -i -y --arg n 3 '.["folder"+$n] += 1' counts.txt

or, using more descriptive long options,

yq --in-place --yaml-output --arg n 3 '.["folder"+$n] += 1' counts.txt

To get the current count associated with folder n:

yq --arg n 3 '.["folder"+$n]' counts.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .