Reputation: 21
I have just started to learn how to use awk to parse and print text file .
I have started with bellow code who can help me ?
NB: quote are mandatory at output file ( see desired output )
awk '/^IPDATA=/ && /A|B|C| '{print "ADD IP ="$0"\n(\n \Ref "$1",Type vlan="$2"\"\n)\n"}' file > file1
NB: Ref is the sum of line of IPREF here in the example we have three : [2] && [2] && [1].
the sample text file in fact is huge but I have summurized it :
IPDATA=A IPID A
IPDATA=A IPREF [2] =
--- IPREF = VRID=A_1
--- IPREF = VRID=A_2
IPDATA=B IPID B
IPDATA=B IPREF [2] =
--- IPREF = VRID=B_1
--- IPREF = VRID=B_2
IPDATA=C IPID C
IPDATA=C IPREF [1] =
--- IPREF = VRID=C_1
I want to get bellow result :
"ADD IP=A "
( Ref 2
"Type vlan=VRID=A_1"
"Type vlan=VRID=A_2"
)
"ADD IP=B "
( Ref 2
"Type vlan=VRID=B_1"
"Type vlan=VRID=B_2"
)
"ADD IP=C "
( Ref 1
"Type vlan=VRID=C_1"
)
thanks
Upvotes: 2
Views: 137
Reputation: 133428
Could you please try following, written and tested with shown samples only in GNU awk
.
awk -v s1="\"" '
/^IPDATA/ && /IPID .*/{
if(FNR>1){ print ")" }
print s1 "ADD IP" s1 "="s1 $NF OFS s1
next
}
/^IPDATA.*IPREF.*\[[0-9]+\]/{
match($0,/\[[^]]*/)
print "( Ref sum of IPREF " substr($0,RSTART+1,RLENGTH-1)
next
}
/^--- IPREF/{
print s1 "Type vlan="$NF s1
}
END{
print ")"
}
' Input_file
Explanation: Adding detailed explanation for above.
awk -v s1="\"" ' ##Starting awk program from here.
/^IPDATA/ && /IPID .*/{ ##Checking condition if line starts IPDATA and having IPID here.
if(FNR>1){ print ")" } ##Checking condition if FNR>1 then printing ) here.
print s1 "ADD IP" s1 "="s1 $NF OFS s1 ##Printing s1 ADD IP s1 equal to s1 last field OFS and s1 here.
next ##next will skip all further statements from here.
}
/^IPDATA.*IPREF.*\[[0-9]+\]/{ ##Checking condition if line starts from IPDATA and having IPREF till [ digits ].
match($0,/\[[^]]*/) ##Using match to match from [ till ] in line.
print "( Ref sum of IPREF " substr($0,RSTART+1,RLENGTH-1) ##printing string as per request and sub-string from RSTART+1 to till RLENGTH-1 here.
next
}
/^--- IPREF/{ ##Checking conditon if line starts from --- IPREF then do following.
print s1 "Type vlan="$NF s1 ##Printing s1 string last field and s1 here.
}
END{ ##Starting END block of this program from here.
print ")" ##Printing ) here.
}
' Input_file ##Mentioning Input_file name here.
Upvotes: 2