Reputation: 8346
I have a file where i am searching for 2 patterns if matched then storing each matched line into array value. But It is not storing values
My Shell command
#Removing new line chars
a=`sed ':a;N;$!ba;s/\n/ /g' sample.txt`
#storing each matched pattern row by row
while read v1; do
y[i]="$v1"
(( i++ ))
done < <(awk -F '<abc>|</abc>' '{for (i=2; i<=NF; i+=2) print $i}' <<< "$a")
Outputs empty values:
echo ${y[0]} is empty
echo ${y[1]} is empty
echo ${y[2]} is empty
it should be
echo ${y[0]} = 1. I am here to show
echo ${y[1]} = 2. I am here to show
echo ${y[2]} = 3. I am here to show
My file is : sample.txt
<abc>
1. I am here to show
</abc>
<no>
</no>
<abc>
2. I am here to show
</abc>
<abc>
3. I am here to show
</abc>
<no>
</no>
Upvotes: 1
Views: 593
Reputation: 207445
I think this is a bit easier on the eye maybe:
#!/bin/bash
declare -a y
while read x; do
y[i]=$x
((i++))
done < <(awk '/^<abc>/ {p=1;next}
/^<\/abc>/ {p=0;next} p' sample.txt)
echo ${y[*]}
In the awk
, the variable p
determines if we are printing the current line. It is set when we find <abc>
and cleared when we find </abc>
.
Upvotes: 1
Reputation: 8346
I found the problem myself...
variable $i
was already set to some value so when i do i++ it was storing the value in to some array index.
i did i=0
then re executed, it works
Upvotes: 0