简体   繁体   English

用unix命令替换所有文件中的ruby代码

[英]replace ruby code in all files with unix command

I have a string !Rails.env.dev? || params['render_javascript'] 我有一个字符串!Rails.env.dev? || params['render_javascript'] !Rails.env.dev? || params['render_javascript'] !Rails.env.dev? || params['render_javascript'] . !Rails.env.dev? || params['render_javascript'] I want to replace this string with render_javascript . 我想用render_javascript替换这个字符串。 It will be lots of work if I do it one file by one file. 如果我一个文件一个文件地做,这将需要很多工作。 I tried to use unix command as follows, but no luck. 我尝试如下使用unix命令,但是没有运气。

for i in $(find . -name "*.rb")
do
       sed 's/!Rails\.env\.dev\? \|\| params\['render_javascript'\]/render_javascript/g' $i > x
       mv x $i
done

Anyone can offer me some help here? 有人可以在这里为我提供帮助吗?

There are few issues in your code/command. 您的代码/命令中几乎没有问题。 First, you are escaping characters unnecessarily. 首先,您不必要地转义了字符。 Second, if we use double quotes to quote sed command it will be better in this case. 其次,如果我们使用双引号对sed命令加引号,则在这种情况下会更好。 You can try below command: 您可以尝试以下命令:

for i in $(find . -name "*.rb")
do
    sed "s/\!Rails\.env\.dev? || params\['render_javascript'\]/render_javascript/g" $i > x 
    mv x $i
done

sed ( GNU sed ) uses Basic Regular expression (BRE) which does not have ? sedGNU sed )使用的Basic Regular expression (BRE)没有? , | | metacharacters, so you do not have to escape them. 元字符,因此您不必逃避它们。 Metacharacters ? 元字符? , | | are added by Extended Regular Expresson (ERE) . Extended Regular Expresson (ERE)

And, I have used double quotes " to quote the sed command, because there are single quotes ' in your search regex. And because double quotes was used to quote the sed command, we also have to escape the ! character. We have to escape ! because it is a shell special character and expands to something else, even before sed command is run. 而且,我已经使用双引号"来引用sed命令,因为搜索正则表达式中有单引号' 。并且由于使用了双引号来引用sed命令,我们还必须转义!字符。我们必须转义!因为它是shell的特殊字符,并且即使在运行sed命令之前也会扩展为其他字符。


If you want to use Extended regular expression (ERE) , then you can use -r option with the sed command. 如果要使用Extended regular expression (ERE) ,则可以在sed命令中使用-r选项。 In this case, you have escape ? 在这种情况下,您有逃脱? and | | character. 字符。 For example: 例如:

sed -r "s/\!Rails\.env\.dev\? \|\| params\['render_javascript'\]/render_javascript/g" $i > x 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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