While appending some text after a matched pattern, I wanted to add an empty line with a comment to isolate my additions from the rest. However, I have noticed that for the very first
\n, I need to escape the
\ with an additional
\ (makes it
\\n) but this is apparently not required for rest of the appended text. Why is this so?
An example that I produced on a SUSE 11 server (bash v3.2.57(2) and GNU sed version 4.1.5) is:
edwdev@hdpedge1:/edw> sed '/test/a \\nNot a test\nJust Playing' <<< test test Not a test Just Playing
If I do not escape the first
\n (right after the
a sed command, I get an n printed instead of a newline.
edwdev@hdpedge1:/edw> sed '/test/a \nNot a test\nJust Playing' <<< test test nNot a test Just Playing
Notice that I have intentionally added a space after
a command so that it doesn't conflict accidentally with alternate syntax.
Same behavior is observed if I replace
\t.Number of spaces after
a command do not seem to matter; the first backslash needs to be escaped to print the special character even after multiple spaces.
Same is the case on another environment, where I originally observed this; a Centos 7 x64 VM, bash version is 4.2.46(2) and sed version is GNU sed 4.2.2
sed -i '/\[mysqld\]/a \\n# <<INSERTED MANUALLY>>\ntransaction-isolation=READ-COMMITTED\ninnodb_flush_method=O_DIRECT\nmax_connections=550\n# <<END OF MANUAL INSERTIONS >>\n' /etc/my.cnf
... [mysqld] # <<INSERTED MANUALLY>> transaction-isolation=READ-COMMITTED innodb_flush_method=O_DIRECT max_connections=550 # <<END OF MANUAL INSERTIONS >> ...
Output Without Escaping first \n:
[mysqld] n# <<INSERTED MANUALLY>> transaction-isolation=READ-COMMITTED innodb_flush_method=O_DIRECT max_connections=550 # <<END OF MANUAL INSERTIONS >>
Is there any particular reason for this behavior? I am unable to find any details while skimming through the docs (here), through, admittedly, I haven't read the entire documentation thoroughly.