In recent past I am not using shell scripts and thus lost touch with powerful search replace options for patters.
As Windows Find replace options doesn’t support much of regex stuff, I resorted to VIM.
My intention to fix an XML file in structured format.
I have an xml file with elements like following (it is just a snippet of big file)
<PolicyNo>012345678</PolicyNo>
<DateOfCommencement>03DEC1983</DateOfCommencement>
<Plan_Term>579-60</Plan_Term>
<SumAssured>2,00,000</SumAssured>
<GrievanceRedressalOfficer>011-57293184</GrievanceRedressalOfficer>
And I wanted it in the format of
<DataPoint PolicyNo=”012345678”></DataPoint>
<DataPoint DateOfCommencement=”03DEC1983”></DataPoint>
<DataPoint Plan_Term=”579-60”</DataPoint>
<DataPoint SumAssured=”2,00,000”></DataPoint>
<DataPoint GrievanceRedressalOfficer=”011-57293184”</DataPoint>
Following expression did the trick. I got to tweak second back reference little a bit for different cases where non special characters are present.
And I could also prefix line numbers to confine operations to limited set of lines
like
:9,26s…..
:s/<\(\w\+\)>\(.\+\)<\/\(\w\+\)>/<Detail \1=”\2”><\/Detail>/gc
As usual this is a simple search replace syntax in the format of :s/<find string>/<replace string>/<options in this case gc>
Here find string is formatted as
- starting with ‘<’
- start of first back reference \(
- word of one of more length \w\+
- close of first back reference \)
- ending with ‘>’
- start of second back reference <\
- characters repeated till character ‘<’. I changed this for few lines
- escape for close charcter ‘/’
- closing tag. Though this is need not be back reference. I just did it
- ending with >
Now replace string is
- “<Detail “
- First back reference \1
- followed by ‘=’
- followed by opening quotes “
- second back reference ‘\2’
- followed by closing quotes ‘”’
- Closing tag syntax.
And the options include
g – all occurrences in a line
c – seek confirmation
Following links might be useful
And my favorite regex site Regular Expressions Reference
No comments:
Post a Comment