I’m experimenting with bash scripts, need help solving this:
i have the following data in a text file: (test.txt)
have.a.nice.day.a=42and55
have.a.nice.day.b=0
have.a.nice.day.c=55and67
go.to.sleep.a=111
go.to.sleep.b=2and122and33
go.to.sleep.c=64
i want to separate the strings from their matching scores and the scores from their delimiters (in this case: “and”) and pick the string with highest score from each group.
in this case it would be “have.a.nice.day.c” for group “have.a.nice.day” and “go.to.sleep.b” for group “go.to.sleep”
so i thought best thing to do would be to separate the elements and assign them variables recursively. like so:
#!/bin/bash
names=$(cat test.txt | grep -o -P '.+(?==\d+)')
for name in $names
do
echo -n "$name"" "
scores=$(cat test.txt | grep -o -P '(?<='$name'=).+')
for scores_group in $scores
do
single_score=$(echo $scores_group | grep -o -P '\d+')
for score in $single_score
do
echo -n "$score"" "
done
echo
done
done
the output would be:
have.a.nice.day.a 42 55
have.a.nice.day.b 0
have.a.nice.day.c 55 67
go.to.sleep.a 111
go.to.sleep.b 2 122 33
go.to.sleep.c 64
but now i have no idea how to find the best score for each group.
thanks
So your actual question, I think, is how do you take “input text” that you’ve labelled as “output”, and find the line with the highest number?
Assuming your output is the input, I’d do this with awk:
Or, broken out in order to explain:
Will this do? Or do you really want to achieve this in pure bash? If so, the awk above can be expressed with the bash below: