-1

I have the input XML file which looks like below

INPUT XML FILE

<Formula>
<Name>Total Hate Fee</Name>
<Code>1234>
<Job>BO</Job>
<Type>sub</Type>
</Formula>


<Formula>
<Name>Total BO Fee</Name>
<Code>1234>
<Job>BO</Job>
<Type>sub</Type>
</Formula>


<Formula>
<Name>Total BO Fee</Name>
<Code>1234>
<Job>BO</Job>
<Type>sub</Type>
</Formula>

I want my shell script to search the pattern "Total Hate Fee" and if the pattern is found then i would like to comment that particular line add <!-- and --> just at the pattern match so that my output looks like below

OUTPUT XML FILE

<Formula>
<--<Name>Total Hate Fee</Name>-->
<Code>1234>
<Job>BO</Job>
<Type>sub</Type>
</Formula>


<Formula>
<Name>Total BO Fee</Name>
<Code>1234>
<Job>BO</Job>
<Type>sub</Type>
</Formula>


<Formula>
<Name>Total BO Fee</Name>
<Code>1234>
<Job>BO</Job>
<Type>sub</Type>
</Formula>

Can anyone help me out on this? Please note I do not want to use xmlstartet tool. Instead I want to use shell scripting

2
  • I purged all the comments. If you need to clarify the question, then please edit the question. I'm also confounded by your refusal to use a tool specifically written to work with XML files. I would also appreciate it if you could keep to a single user account, and not switch between three different ones. It makes your issue easier to track. – Kusalananda Mar 15 at 12:09
0

You were almost there. I just added the second line of ed code which is looking 4 lines below the matched line.

printf '%s\n' \
    'g/Total Hate Fee/-1 s/^/<!--/' \
    'g/Total Hate Fee/+4 s/$/-->/' \
    'w newfile.xml' 'q' \
| ed -s file.xml;
0
awk -v pattern="$yourMatch" '
    $0 ~ pattern{ $0= "<!--" $0 "-->" }1' infile

Note that, at above pattern, would match as regex against the $0 we used; to use pattern as string instead, use as following:

awk -v string="$yourMatch" '
    { if(index($0, string)) $0= "<!--" $0 "-->" }1' infile
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.