while read line out of scope

153 views Asked by At

I call a script with several parameters. The first param, e.g. 4011, is a string which I'm searching in the input file. From there on I just delete all lines starting with ";" until the next match on the pattern "[.*]" is found.

But it seems that also the next ";" lines are deleted within the next match, e.g. [4012]

Any suggestions for how to fix my code?

#!/bin/bash
sip="/Desktop/template/test.conf"
extension=$1
prov=$2
useragent=$3
dest=$4
mac=$5
name=$6

startline=$(grep -n "\[$extension\]" $sip | cut -d : -f 1)
startline=$(($startline+1))
echo $startline

while read line
do
    if [[ ! $line =~ \[.*\] ]]
    then
        if [[ $line = \;* ]]
        then
            sed -i "/$line/d" $sip
        fi
    else
        echo "break"
        break
    fi
    echo $line
done < <(tail -n +$startline $sip)

# Comments
match="\[$extension\]"
insert1=";mac="$mac
insert2=";model="$useragent
insert3=";dest="$dest
insert4=";name="$name
sed -i "/$match/a$insert1\n$insert2\n$insert3\n$insert4" $sip

Example input:

[4002]
sometext
sometext
sometext
sometext
sometext
sometext


[4010]
;mac=aaaaaaaaaaa.xml
;model=spa941
sometext
sometext
sometext
sometext

[4011]
;mac=a44c119fffbe
;model=spa504g
;dest=usmi
;name=1
sometext
sometext
sometext
sometext

[4012]
sometext
sometext
sometext
sometext
sometext
sometext

[4013]
sometext
sometext
sometext
sometext
2

There are 2 answers

2
Jason Hu On

As far as i am concerned, this is a text format very close to .ini files. you don't even need such a long bash code to achieve this. let me show you my solution:

code=4012
sed -n -e '/^\['"$code"'\]/,/^\[.*\]/p' your_file | sed -e '/^$/d' -e '/^;/d' -e '/^\[.*\]/d'

here is my result, with your text file above as input:

$ code=4011
$ sed -n -e '/^\['"$code"'\]/,/^\[.*\]/p' testfile | sed -e '/^$/d' -e '/^;/d' -e '/^\[.*\]/d'
sometext
sometext
sometext
sometext

explanation:

the command consists of two parts of sed, with a pipe connected.

the first part gets all the texts within [] from your specified code to the next [].

then after the pipe, the code deletes empty lines, commented lines, and the [] lines and output you nice results.

1
Marek Židek On
found=0
while read line; do
    if grep "\['"$1"'\]"; then
        shift
        found=1
    elif grep "\[.*\]"; then
        found=0
    elif [ $found -eq 1 ]; then
        echo "$line" | sed 's/^;.*$//' >> /tmp/$$
    else
        echo "$line" >> /tmp/$$
    fi
done < "$file" 
        mv /tmp/$$ "$file"

Hi, this is just a general idea. I hope it'll help, if u want the [4012..] numbers there, u could add another echos in the first two ifs.