bash 我可以从终端快速搜索/替换多个 .txt 文件吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11895169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:58:18  来源:igfitidea点击:

Can I search/replace in multiple .txt files quickly from Terminal?

macosbashterminalreplace

提问by Lizza

I have about 100 .txt files that contain plain text. Somehow, some of the data has been corrupted and needs to be found/replaced.

我有大约 100 个包含纯文本的 .txt 文件。不知何故,某些数据已损坏,需要找到/替换。

I need to search for the characters'--' and replace it with a long dash: '—'.

我需要搜索字符“--”并用长破折号替换它:“-”。

Is there a way to do this quickly with a command in terminal?

有没有办法在终端中使用命令快速执行此操作?

The names of the .txt files in my directory are numbered sequentially: 1.txt, 2.txt, etc.

我的目录下.txt文件的名字是按顺序编号的:1.txt、2.txt等。

Thanks!

谢谢!

回答by Steve

GNU sed:

GNU sed:

sed -i 's/--/—/g' *.txt

OSX BSD sed:

OSX BSD sed

You need to specify a backup file extension. To create a backup file with the extension: .txt.bak:

您需要指定备份文件扩展名。要使用扩展名创建备份文件.txt.bak

sed -i '.bak' 's/--/—/g' *.txt

To completely replace the files, specify an empty extension:

要完全替换文件,请指定一个空扩展名:

sed -i '' 's/--/—/g' *.txt

回答by ajd

sed -i 's/--/–/g' *.txtought to work. The -iflag to sedmakes it act on the files in-place, the sstands for substitute, and the gmakes it replace multiple occurrences of the pattern on the same line. Look up sed's documentation for more information.

sed -i 's/--/–/g' *.txt应该工作。该-i检举sed使得它作用于原地的文件,该s代表的替代品,并g使得它取代在同一行模式的多次出现。查阅sed的文档以获取更多信息。

EDIT:This works on GNU/Linux; it turns out that the syntax is slightly different on OSX (see comments and accepted answer).

编辑:这适用于 GNU/Linux;事实证明,OSX 上的语法略有不同(请参阅评论和接受的答案)。