-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

Kusalananda
  • 333,661
  • 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 '21 at 12:09
  • Related: https://unix.stackexchange.com/questions/638522/replace-tag-of-and-xml-file-after-pattern-matching-using-shell/638564#638564 – Kusalananda Mar 15 '21 at 12:12

2 Answers2

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
αғsнιη
  • 41,407
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;
guest_7
  • 5,728
  • 1
  • 7
  • 13