myol
myol

Reputation: 9838

Sed insert blank line below search string then insert string on the next line

I have a sed expression in a function that I pass parameters to.

insert_after_new_line() {
    if ! grep -q "${2}" "${3}"; then
        sed -i "/${1}/{N;N;a ${2}}" "${3}"
    fi
}

insert_after_new_line search insert textfile.txt

I am trying to have a blank line inserted below the search string and the insert string inserted after.

so

text
text
search
text

becomes

text
text
search

insert
text

but I keep getting the error

sed: -e expression #1, char 0: unmatched `{'

Upvotes: 1

Views: 641

Answers (3)

Kent
Kent

Reputation: 195179

this should work:

sed -i '/search/{G;ainsert 
}' file

You can replace the text by shell variable, but replace the single quotes by double quotes too.

Upvotes: 1

Incrivel Monstro Verde
Incrivel Monstro Verde

Reputation: 948

I tested this. works in command line

sed -i  '/search/a \\ninsert' file

Upvotes: 4

KamilCuk
KamilCuk

Reputation: 141493

sed really delimiters commands by a newline. There is a ; but it does not work for all commands, mostly these which take file name as an argument. ; does not work for r R or for example a. Sed will read everything after a command, so sed interprets is like a ${2}} as a single command, in result it does not find enclosing }, cause it's been eaten by a command. You need a newline:

sed -i "/${1}/{N;N;a ${2}
}" "${3}"

or

sed -i "/${1}/{N;N;a ${2}"$'\n'"}" "${3}"

Upvotes: 2

Related Questions