在 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
Execute a cat command within a sed command in Linux
提问by amar
I have a file.txt
that 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.txt
and replacing that with the string cat file.txt
, but I want contents of file.txt
instead.
这是在 中搜索匹配的字符串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 sed
using the r
command. 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.
读取发生在“每行”循环结束时。