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.

3
  • It is always good to post expected output in CODE TAGS too. Commented Jul 31, 2018 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! 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. Commented Jul 31, 2018 at 12:20
  • Have a look at the following two answers that give you some insight how you could attack this problem using xmlstarlet. (answer 1 and answer 2). Note, these answers are not the solution to your problem but show a methodology. Commented Jul 31, 2018 at 12:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

so don't use / as the sed delimiter, use some other char, e.g. :</Remote>:a ...
You have to add "\" if you're using other delimiter than / sed '\:</Remote>:a ...'
I feel like that's better than having to escape characters within the regexp you're trying to match.
Thanks Guys, solution suggested by JUSHJUSH worked perfectly! Thanks once again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.