Let's start with a simple bash syntax:
Below is the values i have in the array
Ok, so we have a bash array:
arr=(
10.106.86.93,A1,3
10.106.86.93,A2,3
10.106.86.93,A2,3
10.106.86.93,A3,3
10.106.86.93,A3,3
10.106.86.93,A4,3
)
Need to loop through this
Ok. First we need to output the array as newline separated list. The following will output the array:
$ printf "%s\n" "${arr[@]}"
Then we need to read the array elements and split them on the comma separator. We ise IFS
variable to control on which characters bash splits elements:
printf "%s\n" "${arr[@]}" |
while IFS=, read -r ip A num; do
: # TODO body
done
Ok. Now we can check the value of the third column and output the third if it matches 3:
printf "%s\n" "${arr[@]}" |
while IFS=, read -r ip A num; do
if [ "$num" = 3 ]; then
echo "$A"
fi
done
Note that each space is important. The if [[${StatusValue} == "3"}]] then
from your code is very invalid - you need a space between [[
and ${..
and a space between "3"
and ]]
, the }
is invalid. Remember, you talk to the computer using your keyboard, nothing more - each keystroke counts.
Now the hard part:
if the last value is equal 3 then have to merge the value of the second column
Well, this is simply and fastly done with awk
scripting. What we need to do, is to create a map. We need to map third column value to other two columns.
But let's make a simple, stupid and very, very slow approach:
- Identify unique values in the third column
- For each unique value in the third column
- Get all the lines with this value as the third column
- Get the first column from any of the lines
- From the filtered lines extract second column and concatenate them
- Output a line
# just to have the array as a string
arrstr=$(printf "%s\n" "${arr[@]}")
# cut only the third column and get unique values
<<<"$arrstr" cut -d, -f3 | sort -u |
# for each unique third column value
while read -r num; do
# get the columns that have that value as the third column
filtered=$(<<<"$arrstr" awk -vIFS=, -vOFS=, '$3 = '"$num")
# get the values of the second field only
# substitute newline for comma
# remove the trailing comma
second_field_sum=$(<<<"$filtered" cut -d, -f2 | tr '\n' ',' | sed 's/,$//')
# get the value of the first field (from the first line)
ip=$(<<<"$filtered" head -n1 | cut -d, -f1)
# output
printf "%s %s %s\n" "$ip" "$second_field_sum" "$num"
done
Please check your script on shellcheck.net for errors. Most beginners error (missing quotes, typos, bad redirections, if
syntax errors) are easy to fix with just listening to shellcheck messages.