2011-06-05 64 views
1

我使用sed从模板文件创建文件。我无法弄清楚,使用man sed,为什么它不会更改所有匹配的字符串。sed只替代首次出现的字符串

如果我的文件(template_file.txt)包含:

#!/bin/sh 
# 
# /etc/init.d/%SCRIPT_NAME% - Startup script for play %SCRIPT_NAME% engine 
# 
### BEGIN INIT INFO 
[...] 
EOF 

使用:

sed -e "s;%SCRIPT_NAME%;script_test_name;" template_file.txt > script_test_name 

主要生产(script_test_name):

#!/bin/sh 
# 
# /etc/init.d/script_test_name - Startup script for play %SCRIPT_NAME% engine 
# 
### BEGIN INIT INFO 
[...] 
EOF 

我看到了线,有2个乘以要替换的字符串,只替换第一个字符串。

你能给我一个提示如何解决它吗?

回答

5

s命令仅更改第一个匹配项,除非您为其添加g(全局)修饰符。

sed -e "s;%SCRIPT_NAME%;script_test_name;g" template_file.txt > script_test_name 
3

您必须将 “G” 修改器添加到替代:

sed -e "s;%SCRIPT_NAME%;script_test_name;g" template_file.txt > script_test_name 

(注意:在模板中的最后一个 “G”)。这指示sed替换该行中的所有匹配文本。