Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

regex - sed replace token in a multiline file with the contents of another file

File 1:

<!doctype html><html lang="en"><head><meta name="REPLACE_ME"></head><body></body></html>

File 2:

<meta name="A" content="A1"><meta name="B" content="B1">

I am trying to replace the <meta name="REPLACE_ME"> in File 1 with the entire contents of File 2.

Expected result:

<!doctype html><html lang="en"><head><meta name="A" content="A1"><meta name="B" content="B1"></head><body></body></html>

If File 1 had multiple lines I have this working with something like this:

TOKEN="<meta name=\"REPLACE_ME\">"
sed -e "/${TOKEN}/r file2" -e "/${TOKEN}/d" file1

The issue I am having is figuring out how to do this with sed when things are NOT on separate lines in File 1.

Have this as my last attempt:

TOKEN="<meta name=\"REPLACE_ME\">"
sed "s/${TOKEN}/$(sed -e 's/[&/]/\&/g' -e 's/$/\n/' file2 | tr -d '
')/" file1

However, is funky and uses tr which I would like to avoid. Any help would be greatly appreciated.

question from:https://stackoverflow.com/questions/65839929/sed-replace-token-in-a-multiline-file-with-the-contents-of-another-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As others have commented, you should use a dedicated html parser for this but with your limited sample data, it is possible to achieve what you need with sed:

sed -zrn 's@
@@g;s@(^.*<head>)('"$TOKEN"')(</head>.*</html>)(<meta.*$)@143@p' <(cat file1 file2)

Redirect a single input stream into sed and consume as one line with (-z) First remove any newlines and then split the line into 4 section described in parenthesis using regular expressions (-r or -E) and utilising the variable TOKEN. Replace the line for sections 1 followed by 4 and 3.

I know there should be no need to use cat to direct as one stream as sed should see the files as one stream unless -s is used but I was having trouble when splitting the line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...