3

我使用sed替换文件中的文本。我想给 sed 一个文件,其中包含要在给定文件中搜索和替换的所有字符串。

它遍历 .h 和 .cpp 文件。在每个文件中,它会搜索包含在其中的文件名。如果找到,它将例如用“<ah>”(不带引号)替换“ah”。

脚本是这样的:

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 版本的所有命令。

4

3 回答 3

6

您可以消除其中一个循环,因此sed每个文件只需要调用一次。使用该-f选项指定多个替换:

For /F %%y in (all.txt) do 
    sed -i -f allFilesWithHAsSedScript.sed %%y

allFilesWithHAsSedScript.sed源自allFilesWithH.txt并将包含:

s/\"file1\"/"\<"file1"\>"/
s/\"file2\"/"\<"file2"\>"/
s/\"file3\"/"\<"file3"\>"/
s/\"file4\"/"\<"file4"\>"/

(在文章Common threads: Sed by example, Part 3中有很多 sed 脚本的示例和解释。)

不要混淆(双关语)。

于 2009-10-06T11:36:03.277 回答
4

sed本身无法从文件中读取文件名。我不熟悉 VxWorks shell,我想这与缺乏答案有关......所以这里有一些可以在 bash 中工作的东西 - 也许 VxWorks 会支持其中之一。

sed -i 's/.../...' `cat all.txt`

sed -i 's/.../...' $(cat all.txt)

cat all.txt | xargs sed -i 's/.../...'

sed实际上,如果它完成了工作,多次调用也没什么大不了的:

cat all.txt | while read file; do sed -i 's/.../.../' $file; done

for file in $(cat all.txt); do   # or `cat all.txt`
    sed -i 's/.../.../' $file
done
于 2009-10-05T14:50:26.653 回答
0

我要做的是使用 sed 将 allFilesWithH.txt 更改为 sed 命令。

(当被迫使用 sed。我实际上会使用 Perl,它也可以搜索 *.h 文件。)

于 2009-10-06T07:55:42.707 回答