3

I have a list of groups, in which I have people's names:

group1="Kyliane Justine Noemie Marion" group2="Julie Lilou" group3="Lena Celeste" 

and so on...

I want to check how many times the name of a person of a group appears in a file that is named according to the group number (ex: group1.txt).

So I have:

for person in $group1 do number=$(grep -oi "$person" /path/group1.txt | wc -l) echo $person "wrote" $number "times." done 

that works fine.

BUT, what I would like, is to check each group members in each group file, not only $group1 in /path/group1.txt, but also $group2 in /path/group2.txt, and so on... I know I can copy-paste my code and just change group1 by group2, group3, and so on. But I'm sure there is a quicker way especially as I have 12 groups! I'm a beginner in bash and I don't know how to do that.

Thanks a lot for your help.

1
  • for person in "$group1" "$group2" "$group3"? Commented Nov 7, 2018 at 3:08

1 Answer 1

1

Use an array instead of separate variables.

groups=("Kyliane Justine Noemie Marion" "Julie Lilou" "Lena Celeste") i=1 for group in "${groups[@]}" do for person in $group do number=$(grep -oi "$person" /path/group$i.txt 2>/dev/null | wc -l) echo $person "wrote" $number "times." done i=$((i+1)) done 

As a general rule, whenever you find yourself creating variables with sequential names, you probably should be using an array or similar data structure. This applies across most programming languages.

Sign up to request clarification or add additional context in comments.

4 Comments

Probably a typo, probably you ment "${groups[@]}".
Thanks, however there is an issue. I also need this part to change according to the group number: number=$(grep -oi "$person" /path/group1.txt | wc -l)
I thought about fixing it by doing that number=$(grep -oi "$person" path/group$i.txt.html | wc -l) and adding i=$((i+1)) just before the last done. But if for example group4 doesn't exist, then I get an error...
Redirect stderr and you won't see the error message.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.