Search code examples
linuxshellfilesedinsert

SED: Insert a string with special character


I want to INSERT a string with "'" as special character in multiple files. All the files in which I want to insert have a line after which I want to perform my INSERT.

eg:

File Before INSERT:
...
FROM LOCAL :LOAD_FILE
REJECTED DATA :REJECT_PATH
...
File After INSERT:
...
FROM LOCAL :LOAD_FILE
DELIMITER AS '|'
REJECTED DATA :REJECT_PATH
...

I've tried writing down many SED commands but they are generating errors. One of them is:

sed 'LOAD_FILE/a/ DELIMITER AS \'\|\'/g' SOURCE > DESTINATION


Solution

  • Using surrounding double quotes:

    sed "/FROM LOCAL :LOAD_FILE/s//&\nDELIMITER AS '|'/" file
    

    or single quotes (safer to avoid unwanted variable expansion):

    sed '/FROM LOCAL :LOAD_FILE/s//&\nDELIMITER AS '"'|'"'/' file