在Mac和Linux上以递归方式搜索和替换文本文件 [英] Recursive search and replace in text files on Mac and Linux
问题描述
在linux shell中,以下命令将递归搜索并将"this"的所有实例替换为"that"(我面前没有Linux shell,但应该这样做).
In the linux shell, the following command will recursively search and replace all instances of 'this' with 'that' (I don't have a Linux shell in front of me, but it should do).
find . -name "*.txt" -print | xargs sed -i 's/this/that/g'
在OSX上类似的命令会是什么样子?
What will a similar command on OSX look like?
推荐答案
OS X使用了BSD和GNU工具的混合,因此最好始终检查文档(尽管我认为less
甚至不符合OS X联机帮助页):
OS X uses a mix of BSD and GNU tools, so best always check the documentation (although I had it that less
didn't even conform to the OS X manpage):
sed将-i
之后的参数用作备份的扩展名.为没有备份提供一个空字符串(-i ''
).
sed takes the argument after -i
as the extension for backups. Provide an empty string (-i ''
) for no backups.
以下应做:
LC_ALL=C find . -type f -name '*.txt' -exec sed -i '' s/this/that/ {} +
-type f
只是一个好习惯;如果给sed一个目录,sed会抱怨.
-exec
比xargs
更可取;您无需打扰-print0
或其他任何东西.
最后的{} +
表示find
将所有结果作为参数附加到被调用命令的一个实例中,而不是针对每个结果重新运行它. (一个例外是当操作系统允许的最大命令行参数数被破坏时,在这种情况下,find
将运行多个实例.)
The -type f
is just good practice; sed will complain if you give it a directory or so.
-exec
is preferred over xargs
; you needn't bother with -print0
or anything.
The {} +
at the end means that find
will append all results as arguments to one instance of the called command, instead of re-running it for each result. (One exception is when the maximal number of command-line arguments allowed by the OS is breached; in that case find
will run more than one instance.)
这篇关于在Mac和Linux上以递归方式搜索和替换文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!