Bash:有什么命令可以替换文本文件中的字符串吗? [英] Bash: any command to replace strings in text files?
问题描述
我有一个包含许多文本文件的目录层次结构.每次出现在其中一个文件中时,我想搜索特定的文本字符串,并将其替换为另一个字符串.例如,我可能想用Pepsi"替换每个出现的字符串Coke".有谁知道如何做到这一点?我想知道是否有某种 Bash 命令可以做到这一点,而无需在编辑器中加载所有这些文件,或者想出一个更复杂的脚本来做到这一点.
I have a hierarchy of directories containing many text files. I would like to search for a particular text string every time it comes up in one of the files, and replace it with another string. For example, I may want to replace every occurrence of the string "Coke" with "Pepsi". Does anyone know how to do this? I am wondering if there is some sort of Bash command that can do this without having to load all these files in an editor, or come up with a more complex script to do it.
我找到了这个页面 使用 sed 解释一个技巧,但它似乎不适用于子目录中的文件.
I found this page explaining a trick using sed, but it doesn't seem to work in files in subdirectories.
推荐答案
将 sed
与 find
结合使用.例如:
Use sed
in combination with find
. For instance:
find . -name "*.txt" | xargs sed -i s/Coke/Pepsi/g
或
find . -name "*.txt" -exec sed -i s/Coke/Pepsi/g {} \;
(有关更多信息,请参阅 find 的手册页)
(See the man page on find for more information)
这篇关于Bash:有什么命令可以替换文本文件中的字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!