I am trying to replace a line in a file with multiple lines. When I had only one new line char ( \\'$'\\n ). it worked fine, however when I use two of them, it escapes my sed and the file wont run anymore.
sed 's/TextImLookingFor/My\'$'\nReplacement\'$'\nText/g' /path/to/File.txt
File.txt:
This is a file
TextImLookingFor
look at all this text
DesiredOutput
This is a file
My
Replacement
Text
look at all this text
Actual Output
unexpected EOF while looking for matching ''''
syntax error: unexpected end of file
Using older BSD sed you can do:
sed $'s/TextImLookingFor/My\\\nReplacement\\\nText/' file
This is a file
My
Replacement
Text
look at all this text
This should work with newer gnu-sed as well. However newer gnu-sed may just need:
sed 's/TextImLookingFor/My\nReplacement\nText/' file
这可能对您有用(GNU sed):
sed '/TextImLookingFor/c\My\nReplacement\nText' file
The problem with this command
sed 's/TextImLookingFor/My\'$'\nReplacement\'$'\nText/g' /path/to/File.txt
is that it isn't parsing the way you expect it is.
You cannot escape a single quote inside a single quoted string. You can escape a single quote inside a $'...'
quoted string however (I'm not really sure why).
So the above command does not parse this way (as you might expect):
[sed] [s/TextImLookingFor/My\'$[\nReplacement\'$]\nText/g] [/path/to/File.txt]
instead it parses this way:
[sed] [s/TextImLookingFor/My\]$[\nReplacement\'$]\nText/g' [/path/to/File.txt]
with a mismatched single quote at the end and an unquoted \\nText/g
bit.
That is the cause of your problem.
If you can't just use \\n
in your replacement (your version of sed
doesn't support that) and you need to use $'\\n'
then you would need to use something like
sed 's/TextImLookingFor/My\'$'\nReplacement\\'$'\nText/g' /path/to/File.txt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.