搜索和替换特定文件扩展名上的字符串

Duc*_*uck 5 bash string

我有这个 bash:

  replace="s/AAAA/BBBB/g";
  find myDirectory/. -type f -print0 | xargs -0 sed -i $replace;
Run Code Online (Sandbox Code Playgroud)

这将递归扫描myDirectory树并替换那里文件上所有出现的AAAAwith BBBB。

但我想限制这种情况发生在特定的扩展的文件,例如.txt,.read,.po

我如何施加这个限制?

jor*_*anm 12

您可以使用-namefind 选项来限制基于文件名的匹配。

find myDirectory/. -type f -name '*.txt' -print0 | xargs -0 sed -i "$replace"
Run Code Online (Sandbox Code Playgroud)

对于多个扩展名,您可以使用-o(或)并将它们与().

find myDirectory/. -type f \( -name '*.txt' -o -name '*.read' \) -print0 | xargs -0 sed -i "$replace"
Run Code Online (Sandbox Code Playgroud)

可以进行的另一个改进是使用-exec代替xargs. 这更加便携并且消除了子shell。

find myDirectory/. -type f -name '*.txt' -exec sed -i "$replace" {} +
Run Code Online (Sandbox Code Playgroud)

  • 对于任何在谷歌上搜索的人,要在不使用变量的情况下运行此答案中的最后一行,这里有一个示例,该示例递归地查找所有包含 foo 的 txt 文件并替换为 bar。在末尾添加加号: `find ./ -type f -name '*.txt' -read -writable -exec sed -i "s/foo/bar/g" {} +` (2认同)