Here are my attempts to replace a b
character with a newline using sed
while running bash
$> echo 'abc' | sed 's/b/\n/' anc
no, that's not it
$> echo 'abc' | sed 's/b/\\n/' a\nc
no, that's not it either. The output I want is
a c
HELP!
Special characters, preceded by \ 's will be taken literally. (Like you've done with your parentheses: ( \( \) )). It should look like this: \' . If you find that still doesnt work try: '\'' .
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.
Chapter 34 The sed Stream Editor 34.8 Newlines in a sed Replacement The backslash (\) in the replacement string of the sedsubstitution command is generally used to escape other metacharacters, but it is also used to include a newline in a replacement string. Given the following input line where each item is separated by a tab:
As Ben Blank said, there are only three characters that need to be escaped in the replacement string (escapes themselves, forward slash for end of statement and & for replace all): ESCAPED_REPLACE=$ (printf '%s ' "$REPLACE" | sed -e 's/ [\/&]/\&/g') # Now you can use ESCAPED_REPLACE in the original sed statement sed "s/KEYWORD/$ESCAPED_REPLACE/g"
With the global replacement flag sed replaces all occurrences of the search pattern: As you might have noticed, the substring foo inside the foobar string is also replaced in the previous example. If this is not the wanted behavior, use the word-boundary expression ( \b) at both ends of the search string.
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: sed "s/KEYWORD/$ (echo $REPLACE | sed -e 's/\/\\/g; s/\//\\//g; s/&/\\&/g')/g"
Looks like you are on BSD or Solaris. Try this:
[jaypal:~/Temp] echo 'abc' | sed 's/b/\ > /' a c
Add a black slash and hit enter and complete your sed
statement.
$ echo 'abc' | sed 's/b/\'$'\n''/' a c
In Bash, $'\n'
expands to a single quoted newline character (see "QUOTING" section of man bash
). The three strings are concatenated before being passed into sed as an argument. Sed requires that the newline character be escaped, hence the first backslash in the code I pasted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With