What happens if you escape a character in a SED replace string?

What happens if you escape a character in a SED replace string?

Sed needs many characters to be escaped to get their special meaning. For example, if you escape a digit in the replacement string, it will turn in to a backreference.

How does the shell pass a variable to SED?

(The shell expands the variable, then passes the resulting string to sed; so sed only sees literal text – it has no concept of the shell’s variables.)

Do you have to escape double quotes in SED?

The double quotes are not a problem. The only three literal characters which are treated specially in the replace clause are / (to close the clause), \\ (to escape characters, backreference, &c.), and & (to include the match in the replacement). Therefore, all you need to do is escape those three characters:

Is there a way to escape a keyword in SED?

NOTE: The KEYWORD is a dumb substring with no matches etc. It is not supplied by user. Warning: This does not consider newlines. For a more in-depth answer, see this SO-question instead. (Thanks, Ed Morton & Niklas Peter) Note that escaping everything is a bad idea. Sed needs many characters to be escaped to get their special meaning.

How to use special characters in SED shell?

If you’re in a shell, you might need to double escape $, since it’s a special character both for the shell (variable expansion) and for sed (end of line) echo ‘$.cpp’ | sed “s/\\$//” or echo ‘$.cpp’ | sed ‘s/$//’ => ‘.cpp’. Do not escape ( or ); that will actually make them them special (groups) in sed. Some other common characters include [ ] .

Do you need to use sed to replace a string in Bash?

The reason it’s wrong is the beginning of the first sentence: “In my bash script…”. I had the same question & made the same mistake. If you’re using bash, you don’t need to use sed to do string replacements (and it’s much cleaner to use the replace feature built into bash).

What do I need to escape when using SED in a SH?

You can choose an alternative character as the delimiter by writing, e.g., s~/dir~/replacement~ or \\~/dir~p; you’ll need a backslash before the delimiter if you want to include it in the BRE.