Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk with quotes and spaces in bash script

I've the following output in a bash variable set from a received snmp trap:

echo $var

Nov 27 16:20:34 witness logger: trap: vars: DISMAN-EVENT-MIB::sysUpTimeInstance = 0:6:10:29.06,  SNMPv2-MIB::snmpTrapOID.0 = SNMPv2-SMI::enterprises.11.2.29.2.90.0.10000002, SNMPv2 SMI::enterprises.11.2.29.2.90.1 = "Finished Number", SNMPv2-SMI::enterprises.11.2.29.2.90.2 = "Filter Cirteria: [called='3333']", SNMPv2-SMI::enterprises.11.2.29.2.90.3 = "Cleared", SNMPv2     SMI::enterprises.11.2.29.2.90.4 = "major Over-Flow alert on Finished Number for ['3333']", SNMPv2 SMI::enterprises.11.2.29.2.90.5 = "The Corresponding Metric Value is: 0.5", SNMPv2- SMI::enterprises.11.2.29.2.90.6 = "Over-Flow", SNMPv2-SMI::enterprises.11.2.29.2.90.7 = "Tue Nov 27 16:20:05 CET 2012" 

I'm trying to get the following output in variables:

var1 = "Tue Nov 27 16:20:05 CET 2012"
var2 = "Finished Number"
var3 = "The Corresponding Metric Value is: 0.5"
var4 = "Cleared"
var5 = "major Over-Flow alert on Finished Number for ['3333']"

I was thinking of doing this via awk

based on the snmp OID: enterprises.11.2.29.2.90.4, enterprises.11.2.29.2.90.5, 11.2.29.2.90.6 etc...

but can't seem to extract just the content of the quoted content " "

like image 789
The HCD Avatar asked Jan 14 '23 22:01

The HCD


2 Answers

It seems that you want to match all the strings inside double quotes, which is easiest done with grep:

$ echo $var | grep -o '"[^"]*"'

"Finished Number"
"Filter Cirteria: [called=3333]"
"Cleared"
"major Over-Flow alert on Finished Number for [3333]"
"The Corresponding Metric Value is: 0.5"
"Over-Flow"
"Tue Nov 27 16:20:05 CET 2012"

Explanation:

-o only print the part of the line that matches.

"     # Match opening double quote
[^"]* # Match anything not a double quote
"     # Match closing double quote

Hope this helps you get started.

like image 124
Chris Seymour Avatar answered Jan 21 '23 13:01

Chris Seymour


Perl solution:

echo "$var" | perl -nE 'say "var", ++$x, "=$1" while /(".*?")/g'

Output:

var1="Finished Number"
var2="Filter Cirteria: [called='3333']"
var3="Cleared"
var4="major Over-Flow alert on Finished Number for ['3333']"
var5="The Corresponding Metric Value is: 0.5"
var6="Over-Flow"
var7="Tue Nov 27 16:20:05 CET 2012"
like image 28
choroba Avatar answered Jan 21 '23 14:01

choroba