unixsedora-12170

SED substitute from variable containing special characters


I want to use SED in order to substitute a placeholder (##ERROR_MSG##) contained in a .txt file with the content of a variable ($ERROR_MSG)

here the command I use:

cat FILE.TXT  |  sed "s/##ERROR_MSG##/$ERROR_MSG/"

here what is contained in $ERROR_MSG (contains special characters and is multi line)

ERROR:
ORA-12170: TNS:Connect timeout occurred

ERROR:
ORA-12162: TNS:net service name is incorrectly specified

SP2-0306: Invalid option.
Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}] [edition=value]] where    <logon> ::= <username>[/<password>][@<connect_identifier>]
<proxy> ::= <proxyuser>[<username>][/<password>][@<connect_identifier>]
SP2-0157: unable to CONNECT to ORACLE after 3 attempts, exiting SQL*Plus

I recieve the following error message:

sed: -e expression #1, char 22: unterminated `s' command

Solution

  • The only robust way to do this, which will work with any value of $ERROR_MSG is:

    awk -v old="##ERROR_MSG##" -v new="$ERROR_MSG" 's=index($0,old){$0 = substr($0,1,s) new substr($0,s+length(old))} 1' file