1

I have a text file similar to the example below.

I want to insert

<string>insert-me</string>

at the indicated line.

How can I do it? I tried variations similar to this:

sed "/s/<key>first</key>/\n        <array>/\n/test/g" test.txt

and I keep on getting "bad flag in substitute command" error.

Thanks

sample text file:

<record>
    <key>first</key>
    <array>
        --I want to insert the line here--
        <string>hello</string>
        <string>world</string>
        </array>
</record>
<record>
    <key>second</key>
    <array>
        <string>its</string>
        <string>me</string>
        <string>again</string>
        <string>hello</string>
        <string>world</string>
        <string>again</string>
    </array>
</record>
  • 2
    Your question does not match the sample text. Do you want to change the first (acc. sample text) or the second record (acc. question)? – Mausy5043 Jun 2 '18 at 12:55
  • post the expected result – RomanPerekhrest Jun 2 '18 at 13:10
2

There are several issues here (beyond the general one of trying to parse structured data with regex tools)

  1. if your pattern (or replacement) contains slashes, then you either need to use a different separator for the sed commands, or escape the slashes

  2. sed is (normally) line-oriented, so you can't match across line boundaries unless you pull additional lines into the pattern space with N

  3. matching specific amounts of whitespace is going to make the whole thing even more fragile

So for example you could do:

sed '/<key>second<\/key>/ {N; s/\n[[:blank:]]*<array>/&\n\tinsert-me/;}' test.txt

or (more naturally) using append rather than substitute

sed -e '/<key>second<\/key>/ {N; /<array>/ a\\tinsert-me' -e ';}' test.txt
<record>
    <key>first</key>
    <array>
        --I want to insert the line here--
        <string>hello</string>
        <string>world</string>
        </array>
</record>
<record>
    <key>second</key>
    <array>
        insert-me
        <string>its</string>
        <string>me</string>
        <string>again</string>
        <string>hello</string>
        <string>world</string>
        <string>again</string>
    </array>
</record>

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.