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.
prev
is never assigned with a value. Thusline1="${prev}"
always will show nothing – Edgar Magallon Dec 19 '22 at 23:27*
in... vlan*
means zero or more of the "n" character (so it'd match "... vla", "... vlan", "... vlannnnn", etc). I suspect you meant it to match any string (which would be... vlan.*
in regex), but that's not needed or relevant, since the regex doesn't need to match the entire string, it just has to match somewhere in the string. What are you actually trying to search for? – Gordon Davisson Dec 20 '22 at 01:14"$prev"
,"$line"
,"$line1"
and"$line2"
would be good enough — you don’t need the{
and}
. See${variable_name}
doesn’t mean what you think it does …. – G-Man Says 'Reinstate Monica' Dec 20 '22 at 11:57