单个 sed 命令用于多个替换?
我使用 sed 替换文件中的文本。 我想给 sed 一个文件,其中包含给定文件中要搜索和替换的所有字符串。
它遍历 .h 和 .cpp 文件。在每个文件中,它搜索其中包含的文件名。如果找到,它将用“
脚本是这样的:
For /F %%y in (all.txt) do
for /F %%x in (allFilesWithH.txt) do
sed -i s/\"%%x\"/"\<"%%x"\>"/ %%y
- all.txt - 要在其中进行替换的文件列表
- allFilesWithH.txt - 要搜索的所有包含名称
我不想多次运行 sed (作为 input.txt 中文件名的数量) .) 但我想运行一个 sed 命令并将其传递给 input.txt 作为输入。
我该怎么做呢?
PS 我从 VxWorks Development shell 运行 sed,因此它不具备 Linux 版本所具备的所有命令。
I use sed to substitute text in files.
I want to give sed a file which contains all the strings to be searched and replaced in a given file.
It goes over .h and .cpp files. In each file it searches for file names which are included in it. If found, it substitutes for example "a.h" with "<a.h>" (without the quotes).
The script is this:
For /F %%y in (all.txt) do
for /F %%x in (allFilesWithH.txt) do
sed -i s/\"%%x\"/"\<"%%x"\>"/ %%y
- all.txt - List of files to do the substitution in them
- allFilesWithH.txt - All the include names to be searched
I don't want to run sed several times (as the number of files names in input.txt.) but I want to run a single sed command and pass it input.txt as input.
How can I do it?
P.S I run sed from VxWorks Development shell, so it doesn't have all the commands that the Linux version does.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以消除其中一个循环,因此每个文件只需调用
sed
一次。使用-f
选项指定多个替换:allFilesWithHAsSedScript.sed
派生自allFilesWithH.txt
并包含:(在文章 常见主题:Sed 示例,第 3 部分 有许多带有解释的 sed 脚本示例。)
不要感到困惑(双关语)。
You can eliminate one of the loops so
sed
only needs to be called once per file. Usethe
-f
option to specify more than one substitution:allFilesWithHAsSedScript.sed
derives fromallFilesWithH.txt
and would contain:(In the article Common threads: Sed by example, Part 3 there are many examples of sed scripts with explanations.)
Don't get confuSed (pun intended).
sed
本身无法从文件中读取文件名。我不熟悉 VxWorks shell,我想这与缺乏答案有关......所以这里有一些可以在 bash 中工作的东西 - 也许 VxWorks 会支持其中之一。事实上,如果
sed
完成了工作,多次调用它也没什么大不了的:sed
itself has no capability to read filenames from a file. I'm not familiar with the VxWorks shell, and I imagine this is something to do with the lack of answers... So here are some things that would work in bash - maybe VxWorks will support one of these things.And really, it's no big deal to invoke
sed
several times if it gets the job done:我要做的就是使用 sed 将 allFilesWithH.txt 更改为 sed 命令。
(当被迫使用 sed 时。我实际上会使用 Perl,它也可以搜索 *.h 文件。)
What I'd do is change allFilesWithH.txt into a sed command using sed.
(When forced to use sed. I'd actually use Perl instead, it can also do the search for *.h files.)