bash 使用文件的内容使用 SED 替换字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6790631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:47:09  来源:igfitidea点击:

Use the contents of a file to replace a string using SED

bashunixshellsedterminal

提问by Eric Brotto

What would be the sed command for mac shell scripting that would replace all iterations of string "fox" with the entire string content of myFile.txt.

什么是 mac shell 脚本的 sed 命令,它将用 myFile.txt 的整个字符串内容替换字符串“fox”的所有迭代。

myFile.txt would be html content with line breaks and all kinds of characters. An example would be

myFile.txt 将是带有换行符和各种字符的 html 内容。一个例子是

    </div>
  </div>
  <br>
  <div id="container2">
    <div class="question" onclick="javascript:show('answer2')";>

Thanks!

谢谢!

EDIT 1

编辑 1

This is my actual code:

这是我的实际代码:

sed -i.bkp  '/Q/{
s/Q//g
r /Users/ericbrotto/Desktop/question.txt
}' $file

When I run it I get:

当我运行它时,我得到:

sed in place editing only works for regular files. 

And in my files the Q is replaced by a ton of chinese characters (!). Bizarre!

在我的文件中,Q 被大量汉字 (!) 替换。奇怪!

回答by brandizzi

You can use the rcommand. When you find a 'fox' in the input...

您可以使用该r命令。当您在输入中找到“狐狸”时...

/fox/{

...replace it for nothing...

......无所事事地更换它......

    s/fox//g

...and read the input file:

...并读取输入文件:

    r f.html
}

If you have a file such as:

如果您有一个文件,例如:

$ cat file.txt
the
quick
brown
fox
jumps
over
the lazy dog
fox dog

the result is:

结果是:

$ sed '/fox/{
    s/fox//g
    r f.html
}' file.txt
the
quick
brown

    </div>
  </div>
  <br>
  <div id="container2">
    <div class="question" onclick="javascript:show('answer2')";>
jumps
over
the lazy dog
 dog
    </div>
  </div>
  <br>
  <div id="container2">
    <div class="question" onclick="javascript:show('answer2')";>

EDIT: to alter the file being processed, just pass the -iflag to sed:

编辑:要更改正在处理的文件,只需将-i标志传递给 sed:

sed -i '/fox/{
    s/fox//g
    r f.html
}' file.txt

Some sed versions (such as my own one) require you to pass an extension to the -iflag, which will be the extension of a backup file with the old content of the file:

某些 sed 版本(例如我自己的版本)要求您将扩展名传递给-i标志,这将是具有文件旧内容的备份文件的扩展名:

sed -i.bkp '/fox/{
    s/fox//g
    r f.html
}' file.txt

And here is the same thing as a one liner, which is also compatible with Makefile

这是与单衬相同的东西,它也与 Makefile 兼容

sed -i -e '/fox/{r f.html' -e 'd}'

回答by buddyp450

Ultimately what I went with which is a lot simpler than a lot of solutions I found online:

最终,我采用的方法比我在网上找到的许多解决方案要简单得多:

str=xxxx
sed -e "/$str/r FileB" -e "/$str/d" FileA

Supports templating like so:

支持这样的模板:

str=xxxx
sed -e "/$str/r $fileToInsert" -e "/$str/d" $fileToModify