0

I have been trying to use sed for the following - I am searching in a file for the below keyword -

</Remote>

And right after it, on new line, am trying to insert following -

<ScanConfig filesToTest="ABCD_*.csv" namePatternLogic="0" scanMethod="0" subdirsScanLevel="" />

I have tried standard SED -

sed -i '</Remote>/a <ScanConfig filesToTest="ABCD_*.csv" namePatternLogic="0" scanMethod="0" subdirsScanLevel="" />' somefile.txt

OR

sed -i '\#^ *</Remote> *$# a\ <ScanConfig filesToTest="ABCD_*.csv" namePatternLogic="0" scanMethod="0" subdirsScanLevel="" />' somefile.txt

Both failed with below errors -

sed: -e expression #1, char 1: unknown command: `<'
sed: -e expression #1, char 1: unknown command: `"'

I suspect the special characters in the line I am trying to insert which has <, /> characters is confusing SED. I tried to use escape characters with /\ though it didn't quiet work out.

Can someone please help me with this? Thanks.

  • It is always good to post expected output in CODE TAGS too. – RavinderSingh13 Jul 31 '18 at 10:11
  • First of all welcome to Stack Overflow. We understand that you are excited about parsing XML with regex, [but just do not do it!](https://stackoverflow.com/a/1732454/8344060) Tools such as sed and AWK are extremely powerful for handling text files, but when it boils down to parsing complex-structured data — such as XML, HTML, JSON, ... — they are nothing more than a sledgehammer. Yes, you can get the job done, but sometimes at a tremendous cost. For handling such delicate files, you need a bit more finesse by using a more targetted set of tools. – kvantour Jul 31 '18 at 12:20
  • Have a look at the following two answers that give you some insight how you could attack this problem using [tag:xmlstarlet]. ([answer 1](https://stackoverflow.com/a/51441662/8344060) and [answer 2](https://stackoverflow.com/a/50716547/8344060)). Note, these answers are not the solution to your problem but show a methodology. – kvantour Jul 31 '18 at 12:22

1 Answers1

1

This one should work

sed  -i '/<\/Remote>/a <ScanConfig filesToTest="ABCD_*.csv" namePatternLogic="0" scanMethod="0" subdirsScanLevel="" />' file.txt

In your first script you forgot to add "/" in the beggining of sed expression.

Also you have to use "\/" to match "/" if you're using it as sed delimiter.

JUSHJUSH
  • 367
  • 1
  • 11