开发者

Insert (or append) a line ending with a trailing backslash (\) using sed

On Linux (BusyBox, QNAP-NAS) I want to add some extra path to my .bashrc file via script using sed. The relevant part of the file looks as follows:

[...]
export PATH=\
/bin:\
/sbin:\
/usr/bin:\
/usr/sbin:\
/usr/local/bin
[...]

The extra line to be inserted (at position 4 in the original file) is /opt/bin:/opt/sbin:\. To get this done my sed one-liner looks like this:

sed '4i/opt/bin:/opt/sbin:\\' .bashrc > .bashrc.tmp

, correctly escaping the trailing backslash. Somehow sed converts the remaining \' into a newline eating up the trailing backslash, resulting in:

[...]
export PATH=\
/opt/bin:/opt/sbin:

/bin:\
[...]

Adding a third backslash gives me the trailing backslash, but still adds the newline, so

sed '4i/opt/bin:/opt/sbin:\\\' .bashrc > .bashrc.tmp

results into

export PATH=\
/opt/bin:/opt/sbin:\

/bin:\

If I add an extra space in my sed command

sed '4i/opt/bin:/opt/sbin:\\ ' .bashrc > .bashrc.tmp

everything looks fine, but I get the extra space at the end of line as well.

export PATH=\
/opt/bin:/opt/sbin:\  # extra space here

/bin:\

What did the trick for now is a second sed command removing the trailing spaces

#!/bin/sh

sed -e '4i/opt/bin:/opt/sbin:\\ ' .bashrc > .bashrc.tmp
sed -e 's/[开发者_JAVA百科 \t]*$//' .bashrc.tmp > .bashrc.tmp2  # change \t to real tab

But still I wonder why sed is transforming \' into a newline, and how to solve the above job with a simple one-liner? How can I insert (or append) a line with a trailing backslash using sed? Thanks in advance.


Here's a workaround:

sed '4s|^|/opt/bin:/opt/sbin:\\\n|' .bashrc


If of any help I used four backslashes to append a backslash without space at the ond of a line.

My command looks like this:

sed "1i #backtrace_script\n#!/bin/sh\ngeany -si \\\\" \

which results in

 #!/bin/sh
 geany -si \


Looks like a bug in busybox sed. It works fine with GNU sed 4.2.1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜