0

I'm trying to read a file, with the condition that if my current line has a regex of the below, then print both the current line and previous line. However I do not get any output at all.

$ cat xc
#!/bin/bash
prev=
regex="switchport trunk allowed vlan*"
while read line
do
    if [ -n "${prev}" ] && [[ $line =~ $regex ]];then
        line1="${prev}"
        line2="${line}"
        echo "${line1}"
        echo "${line2}"
    fi
done < as159.tmp

$ ./xc

When testing the condition without the $prev section (i commented it out, as shown below), I can see that I do get output:

$ cat xc
#!/bin/bash
prev=
regex="switchport trunk allowed vlan*"
while read line
do
    #if [ -n  "${prev}" ] && 
    if [[ $line =~ $regex ]];then
        line1="${prev}"
        line2="${line}"
        echo "${line1}"
        echo "${line2}"
    fi
done < as159.tmp

$ ./xc

switchport trunk allowed vlan 40,10,30

switchport trunk allowed vlan 10,20,30,50,100

So it must be a condition problem, which I'm not sure what it is.

1 Answers1

1

The main problem is about your variable prev since this one has never a value. So the solution is to assign it a value like this:

...
while read line
do
    #if [ -n  "${prev}" ] && 
    if [[ $line =~ $regex ]];then
        line1="${prev}"
        line2="${line}"
        echo "${line1}"
        echo "${line2}"
    fi
prev="$line"
done < as159.tmp
...

Btw, using line1="${prev}" and line2="${line}" is redundant (unless you want to manipulate the values without affecting the original variables). So, you can simply use:

...
while read line
do
    #if [ -n  "${prev}" ] && 
    if [[ $line =~ $regex ]];then
        echo "${prev}"
        echo "${line}"
    fi
prev="$line"
done < as159.tmp
...