在 Linux 中的 sed 命令中执行 cat 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17017270/
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-08-06 23:10:40  来源:igfitidea点击:

Execute a cat command within a sed command in Linux

linuxsedcat

提问by amar

I have a file.txtthat has some content. I want to search for a string in file1.txt, if that string is matched I want to replace that string with the content of the file.txt. How can I achieve this?

我有一个file.txt有一些内容的。我想在 中搜索一个字符串file1.txt,如果该字符串匹配,我想用file.txt. 我怎样才能做到这一点?

I have tried using sed:

我试过使用sed

sed -e 's/%d/cat file.txt/g' file1.txt

This is searching for the matching string in the file1.txtand replacing that with the string cat file.txt, but I want contents of file.txtinstead.

这是在 中搜索匹配的字符串file1.txt并将其替换为 string cat file.txt,但我想要的是内容file.txt

回答by Ivan Kolmychek

How about saving the content of the file in the variable before inserting it into sed string?

在将文件插入到 sed 字符串之前,如何将文件的内容保存在变量中?

$content=`cat file.txt`; sed "s/%d/${content}/g file1.txt"

回答by Jonathan Leffler

You can read a file with sedusing the rcommand. However, that is a line-based operation, which may not be what you're after.

您可以sed使用该r命令读取文件。但是,这是基于行的操作,这可能不是您所追求的。

sed '/%d/r file1.txt'

The read occurs at the end of the 'per-line' cycle.

读取发生在“每行”循环结束时。