在Mac和Linux上以递归方式搜索和替换文本文件 [英] Recursive search and replace in text files on Mac and Linux

查看:434
本文介绍了在Mac和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会抱怨. -execxargs更可取;您无需打扰-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆