简体   繁体   中英

Looking for a Perl or sed one-liner to replace a string with contents from another file

In an HTML file, let's call it index.html , I want to replace a comment string, say //gac goes here , with the contents (multi-line) from a separate file which is called: gac.js. Is there a nice one-liner for that?

I found something as: sed -e "/$str/r FileB" -e "/$str/d" FileA , but it is not working as promised.

I do like it as short as possible, as it will be called after an SVN revert (I don't want any of that google.script polluting my development environment).

This should work, even though it is nasty:

perl -pe 'BEGIN{open F,"gac.js";@f=<F>}s#//gac goes here#@f#' index.html

In the case that gac.js is supposed to be dynamic:

perl -pe 's#//(\S+) goes here#open+F,"$1.js";join"",<F>#e' index.html
perl -mFile::Slurp -pe 's/\/\/(\w+) goes here/@{[File::Slurp::read_file("$1.js")]}/;'

显然需要File :: Slurp

不是很好,但似乎工作:

cat index.html | perl -pe 'open(GAC, "gac.js");@gac=<GAC>;$data=join("", @gac); s/gac goes here/$data/g'

After going through man sed , this tutorial and some experimenting I came up with:

sed -i '\_//gac goes here_ {
    r gac.js
    d 
}' index.html

Which does exactly what I want. It's not exactly a oneliner (if i make it one line i get: sed: -e expression #1, char 0: unmatched '{' ) which I don't understand. However expression above fits nicely in my update script.

Lessons learned: sed is very powerfull, -i behaves different on mac os x / linux, /string/ can easily be replaced with \\[other delimiter]string[other delimiter].

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