简体   繁体   English

使用sed将文件替换为字符串,而不使用两个sed命令?

[英]Replacing a string with file using sed, without using two sed commands?

In the process of automating a license header, I have a place holder: /* @@LICENSE_HEADER@@ */ , which I can replace with a file named license with the following: 在自动执行许可证标头的过程中,我有一个占位符: /* @@LICENSE_HEADER@@ */ ,可以用以下文件替换为名为license的文件:

sh-3.2$ sed -e $'/\/\* @@LICENSE_HEADER@@ \*\//{r license\n}' \
-e $'/\/\* @@LICENSE_HEADER@@ \*\//d' file.c

I've cobbled this together from other sources. 我已经从其他来源整理了这个。 Is it possible to replace the string, rather than issuing a second command to delete the line the string appears in? 是否可以替换字符串,而不是发出第二条命令来删除字符串出现的行?

尝试sed -e $'/\\/\\* @@LICENSE_HEADER@@ \\*\\//{r license\\n;d;}' file.c

Sed is sort of a programming language for editing, so you can use more than one command per line. Sed是一种用于编辑的编程语言,因此每行可以使用多个命令。

By the way, I suggest you change the license string to something that doesn't contain any special regular expression characters. 顺便说一句,我建议您将许可证字符串更改为不包含任何特殊正则表达式字符的字符。 Here, I just made it @@@LICENSE NUMBER@@@ , so I don't have to keep escaping the regular expression characters. 在这里,我只是将其设置为@@@LICENSE NUMBER@@@ ,所以不必不必转义正则表达式字符。 After all, it's your string, so you can make it anything you want: 毕竟,这是您的字符串,因此您可以根据需要进行更改:

sed  '/@@@LICENSE NUMBER@@@/ {
r license.txt
d
}' file.c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM