简体   繁体   中英

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'] . I want to replace this string with 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.

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. 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 ? , | metacharacters, so you do not have to escape them. Metacharacters ? , | are added by 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.


If you want to use Extended regular expression (ERE) , then you can use -r option with the sed command. In this case, you have escape ? and | character. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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