4

I'm trying to read an openvpn status log to get connected users. I've tried following the answer here, but no luck.

Here's my file:

OpenVPN CLIENT LIST
Updated,Mon Jul 13 10:53:46 2020
Common Name,Real Address,Bytes Received,Bytes Sent,Connected Since
user123,8.9.10.11:24142,143404433,5616022,Mon Jul 13 10:09:31 2020
ROUTING TABLE
Virtual Address,Common Name,Real Address,Last Ref
192.168.1.2,user123,8.9.10.11:24142,Mon Jul 13 10:53:45 2020
GLOBAL STATS
Max bcast/mcast queue length,1
END

I want the lines between "Common" and "ROUTING", e.g:

user123,8.9.10.11:24142,143455713,5682214,Mon Jul 13 10:09:31 2020

Using this:

awk '/Common/{flag=1;next}/ROUTING/{flag=0}flag' /pathtomylog/openvpn-status.log

I get:

user123,8.9.10.11:24142,143455713,5682214,Mon Jul 13 10:09:31 2020
192.168.1.2,user123,8.9.10.11:24142,Mon Jul 13 11:00:36 2020
GLOBAL STATS
Max bcast/mcast queue length,1
END

Any help appreciated.

Edit: The following code worked perfectly. The issue was the 2nd instance of Common.

sudo awk '/ROUTING/{flag=""} /^Common/{flag=1;next} flag' Input file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93

1 Answers1

3

Could you please try following, written and tested with shown samples in GNU awk.

awk '/ROUTING/{flag=""} /^Common/{flag=1;next} flag' Input_file

Why OP's code didn't work: First flag is getting set by line starting with Common and then again its getting set by string Common which is coming after ROUTING too by which variable flag is getting set again and then its NEVER get unset because ROUTING is NOT found after 2nd Common hence its printing all lines from there. So I changed regex which is looking for /^Common/ which will not that match other line after ROUTING.

Explanation: Adding detailed explanation for above.

awk '             ##Starting awk program from here.
/ROUTING/{        ##Checking if a line starts from string ROUTING then do following.
  flag=""         ##Setting flag value to NULL here. Since we want to STOP printing from here onward.
}
/^Common/{        ##Checking condition if a line starting from Common then do following.
  flag=1          ##Setting variable flag to 1 here.
  next            ##next keyword will skip all further statements from here.
}
flag              ##Checking condition if flag is SET then print current line(since no action mentioned so by default printing of current line will happen) here.
' Input_file      ##Mentioning Input_file name here.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93