Issue
I have a properties file of the form:
group1=A,B,C
group1_count=10
# zero or more number of empty lines
group2=A,E
group2_count=1
...
...
I would like to read the file in a bash script and print something like: group_name:group_count:group_items:
group1:10:A,B,C
group2:1:A,E
Solution
If your input is sorted (removing the need to group items that are presented out-of-order -- which would call for data structures bash 3 doesn't support), you can do something like the following:
#!/usr/bin/env bash
name=
while IFS= read -r line; do
[[ $line = *"#"* ]] && line=${line%%"#"*} # strip comments
[[ $line ]] || continue # skip empty lines
[[ $line =~ ^[[:space:]]+$ ]] && continue # skip lines with only whitespace
new_name=${line%%_*}; new_name=${new_name%%=*}
if [[ $new_name != "$name" ]]; then
if [[ $name ]]; then
echo "${name}:${count}:${groups}"
fi
name=$new_name; count=; groups=
fi
case $line in
*_count=*) count=${line#*_count=} ;;
*=*) groups=${line#*=} ;;
esac
done
echo "${name}:${count}:${groups}"
See this running at https://ideone.com/nrpfLO
Answered By - Charles Duffy