0

I have refer this Grep the lines between the occurrence of the same pattern , I don't want to split into file; instead, I want to store it into an array. File count.txt contain:

0 
1
2
3
0
1
2
0
1

My script code is:

total=$(sed -n \$= count.txt)
c=0
k=0
lineno=0
var="0"
for i in $(cat count.txt);
do
        if ["$i" -eq "$var"]
        then
                arr[$((k++))]=c
                c=0
                c=$((c+1))

        else
                c=$((c+1))
                if ["$lineno" -eq "$total"]
                then
                        arr[$((k++))]=c
                fi
        fi
        lineno=$((lineno+1))
done

The above logic is tested on C++ launguage which on printing the array shows : 0 4 3 2 Firstly, my script is showing error like line 9: [0: command not found. Secondly, is there any efficient method to store the repeated count in array, like above output?

  • 1
    The command not found error is because your [ test lacks the required whitespace: [ "$i" -eq "$var" ] – steeldriver Dec 27 '18 at 13:06
  • @msp9011 I want the output: 4 3 2 in array – Arya Dec 27 '18 at 13:17
  • There is not output instruction; in addition =c is putting the letter c in the variable, may be you want =$c and the first test is right the first time as 0=0 this explains the potential output 0 in sequence instead of 4 3 2. – matzeri Dec 27 '18 at 14:22
1

An awk one-liner:

awk -v patt="0" -v prev=1 '
    $0 ~ patt {print NR - prev; prev = NR} 
    END {print NR + 1 - prev}
' file
0

Try this,

LINES=(`cat count.txt `)
arr=()
arrIndex=0
a=`echo $LINES`
for i in "${!LINES[@]}"; do
if [[ "${LINES[$i]}" = "$a" ]]; then
        arr[arrIndex]=`echo "${i}"`
        arrIndex=$((arrIndex+1))
fi
done
arr[arrIndex]=`echo ${#LINES[@]}`
arrOut=()
for ((i=1; i<"${#arr[@]}"; ++i))
do
        j=`expr $i - 1 `
        arrOut[$i]=`echo "${arr[$i]} ${arr[$j]}" | awk '{a=$1-$2;print a}'`
done

echo ${arrOut[@]}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.