简体   繁体   中英

Trying to print "\n" in bash with sed

Having some problems having sed insert the two-character sequence \\ n . (I'm using bash to create some expect scripts). Anything that I try in a replace pattern ends up as an actual newline character.

I've tried:

sed s/<string>/'\\\\n'/
sed s/<string>/\\\\n/
sed s/<string>/\\n/

And pretty much any permutation that does or doesn't make any sense.

I need it to work with the bash and sed installed on a Mac.

sed s/<string>/'\\\\n'/ works for me with both the Lunix (GNU) and OS X (bsd) versions of sed :

$ echo aXb | sed s/X/'\\n'/
a\nb

sed s/<string>/\\\\\\\\n/ would also work. When bash sees \\\\ (outside of quotes), it treats it as a single escaped backslash, so \\ is actually passed to the command. When it sees \\\\\\\\n , that's just two escaped backslashes followed by "n", so it passes \\\\n to the command. Then, when sed sees \\\\n , it also treats that as an escaped backslash followed by "n", so the replacement string winds up being \\n . Since the "n" is always after any completed escape sequence, it's just treated as another character in the replacement string.

pure code, single quoted

sed 's/Pattern/\\n/' YourFile

Shell interpreted, double quote

sed "s/Pattern/\\\\n/" YourFile

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM