Escape characters in sed stream
I'm trying to use sed on the linux command line, and am running into an issue with special characters.
I'd like to replace "~" with "E;" in the target file (without quotations). So far, using this command: sed {s/\~/\E\;/g} on this data: blah~blah produces: blah~#7E;blah Close, but no cigar. Thanks in advance for any insight you can provide. |
I would first ask how you arrived at the expression you are using? Why does it include "" in the replacement string if you do not want them in the replacement text? And why the curly braces?
And by extension, what happens if you remove those characters, have you tried to do that? |
I don't believe '~' is a special character. At least not when using regular expressions with sed. It is in the Bash shell. It expands the user's home directory. So it doesn't need to be escaped with sed.
FWIW sed -i 's/~/E;/g' file.txt worked for me |
The forum software "edited" my desired target string.
Quote:
The ampersand is the issue, I believe. It is a sed special character. |
The curly braces are the problem (and I've never seen them used with sed before). This works:
Code:
echo blah~blah | sed 's/~/\E;/' Code:
echo blah~blah | sed "s/~/\E;/" Code:
echo blah~blah | sed {s/~/\\\E\;/} Edit: The forum messed up the characters again. |
Thanks all. My ignorance is showing.
|
Just to close this out, curly brackets are used to group commands - typically when a selection criteria is met; say particular line number or regex match. It is a standard, if not everyday, usage in sed.
|
Quote:
You don't need to escape the tilde, '~' for the regular expression, but you do need to escape the ampersand, '&' because it is special, and the semi-colon to hide it from the shell (i.e. for a different reason than the &). The curly braces are unnecessary, but I would suggest single quotes around the whole expression in which case there is no need to additionally escape the tilde and semi-colon as the shell does not see them: Code:
echo 'blah~blah' |sed 's/~/\E;/g' |
Quote:
This doesn't apply in the match pattern - ampersands do not need to be escaped there. (Aside: Some regex engines have a concept of a union operator for combining multiple character classes, and use a double ampersand for this; sed is not one of those.) |
All times are GMT -5. The time now is 07:07 PM. |