有没有办法防止sed添加回车(^ M)?

时间:2016-06-16 08:58:30

标签: php wordpress bash sed

我想在wordpress php文件中define('WP_MEMORY_LIMIT', '96M');之后添加define('WP_DEBUG', false);

这是我到目前为止所尝试的内容:

1 -

sed -b -i "/'WP_DEBUG', false);/a define('WP_MEMORY_LIMIT', '96M');" $full_path/wp-config.php;

2-

 sed -i "s/'WP_DEBUG', false);/'WP_DEBUG', false);\ndefine('WP_MEMORY_LIMIT', '96M');/" $full_path/wp-config.php;

问题是,所有新行都被这个回车符替换。如何在特定行之后添加新行并且没有此问题?

define('WP_DEBUG', false);^M
define('WP_MEMORY_LIMIT', '96M');

使用sed(GNU sed)4.2.2,Ubuntu 16.04

以下是澄清问题的屏幕截图:

enter image description here

enter image description here

注意: 好吧,问题在阅读@ anishsane的回答后解决了。由于原始文件(来自wordpress.org/latest.zip)具有CRLF(windows)行结尾,因此添加\ n正在打破文件视图。使用" \ r \ n"解决了这个问题:

sed -i "s/'WP_DEBUG', false);/'WP_DEBUG', false);\r\ndefine('WP_MEMORY_LIMIT', '96M');/" $full_path/wp-config.php;

我不确定为什么会掉线。请解释一下,所以我可以澄清这个问题。

3 个答案:

答案 0 :(得分:7)

该文件最初具有CRLF行结尾。当您在vim编辑器中打开它时,vim知道该文件具有CRLF结尾& 隐藏来自用户。通过编辑器添加的任何新行也将具有与文件其余部分相同的行结尾。

当您通过sed添加新行时,它会有LF行结尾。下次在vim中打开它时,vim会看到混合行结尾,CRLF& LFvim然后决定将其解释为包含LF行结尾的文件。 &安培;所有CR个字符都会突出显示为^M

进行测试,试试这个:

$ printf '%d\r\n' {1..5} > test_endings # This will create a file with CRLF endings.
$ file test_endings 
test_endings: ASCII text, with CRLF line terminators
$ vim test_endings
1
2
3
4
5
~
~
"test_endings" [dos] 5L, 15C        <~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Notice the word DOS here.

$ echo 6 >> test_endings # This will add line with LF line endings.
$ file test_endings 
test_endings: ASCII text, with CRLF, LF line terminators
$ vim test_endings
1^M
2^M
3^M
4^M
5^M
6
~
~
"test_endings" 6L, 17C

简而言之,问题不在于sed,而在于原始文件。

答案 1 :(得分:1)

尝试将以DOS格式结尾的行转换为unix格式:

sed 's/^M$//' $full_path/wp-config.php > $full_path/wp-config.php

此处有更多方法:http://www.cyberciti.biz/faq/howto-unix-linux-convert-dos-newlines-cr-lf-unix-text-format/

答案 2 :(得分:-1)

经过测试,无法复制。

该文件确实包含在Wordpress本身开始的Windows行结尾。 (见the sample file)。

运行发布的命令(编号2),结果为

define('WP_DEBUG', false);                                                      
define('WP_MEMORY_LIMIT', '96M');^M

这是预期的行为,虽然不是OP原始问题的输出,但正是他们在截图中显示的内容。