Linux,使用替换项目列表在文件文件夹上查找替换? [英] Linux, find replace on a folder of files using a list of items for replacement?
问题描述
我正在寻找一种使用外部列表 (Replace.txt) 来替换/temp 中包含 50 个文件的文件夹中的文本的方法.
I'm looking for a way to use an external list (Replace.txt) to replace text on a folder of 50 files in /temp.
我的替换文件 Replace.txt 将类似于以下内容,但包含 400 多个项目.
My replacement file Replace.txt will be something like the following but contain 400+ items.
Old,New
Apples, Oranges
Mellon, Bananas
Car, Train
例如
我可以使用 sed,但手动添加我的列表效率不高.不知道能不能用类似sed代码的外部文件列表.
I could use sed but adding my list manually would not be efficient. I don't know if you can use an external file list with similar code for sed.
代码:
sed -i 's/item1/itemb/g:s/itemc/itemd/g:s/iteme/itemf/g' *
大家有什么好用的吗?
推荐答案
您可以使用 sed
从输入文件轻松生成 sed
脚本.>
You can easily generate a sed
script from your input file ... using sed
.
sed 's/^/s%/;s/, */%/;s/$/%g/' Replace.txt | sed -f - -i /directory/*
管道中的第一个命令根据您的替换模式生成一个 sed
脚本;看起来像
The first command in the pipeline generates a sed
script from your replacement patterns; it looks like
s%Old%New%g
s%Apples%Bananas%g
然后我们将其提供给另一个 sed
实例,指定标准输入 (-
) 作为从中读取脚本的文件 (-f
>) 以及您要在其中执行这些替换的文件作为文件名参数.
and we then feed this to another sed
instance, specifying standard input (-
) as the file to read the script from (-f
) and the files you want to perform these replacements in as the file name arguments.
s/^/s%/
在行首插入 s%
.s/, */%/
仅用 %
替换第一个逗号(带有可选的尾随空格).s/$/%g/
在每行的末尾添加 %g
.(在正则表达式中,^
匹配行首,$
匹配行尾.)
s/^/s%/
inserts s%
at beginning of line. s/, */%/
replaces the first comma (with optional trailing whitespace) with just %
. s/$/%g/
adds %g
at the end of each line. (In regex, ^
matches the beginning of line, and $
matches the end of line.)
Linux sed
愉快地从标准输入读取脚本;其他一些平台可能会受到阻碍,或者需要像 /dev/stdin
这样的解决方法而不是 -
作为文件名参数.在最坏的情况下,将生成的脚本保存在一个临时文件中,完成后将其删除.
Linux sed
happily reads a script from standard input; some other platforms may be encumbered, or require a workaround like /dev/stdin
instead of -
as the file name argument. In the worst case, save the generated script in a temporary file, then remove it when you're done.
也许会注意到,这会很高兴地将 PineApplesauce
替换为 PineBananasauce
,将 Boldface
替换为 BNewface
.您或许可以围绕 Old
文本设计一个更受约束的正则表达式.另请注意,如果 Old
包含正则表达式元字符,如果您希望 sed
从字面上替换它们,则应将其转义;所以
Perhaps notice that this will happily replace PineApplesauce
with PineBananasauce
and BOldface
with BNewface
. You can perhaps devise a more constrained regular expression around the Old
text. Notice also that if Old
contains regular expression metacharacters, those should be escaped if you want sed
to replace them literally; so
s%your *new* friend%your *old* buddy%
是错误的,应该是类似
s%your [*]new[*] friend%your *old* buddy%
如果意图是将旧"短语解释为字面文本.
if the intent is to interpret the "old" phrase as literal text.
这篇关于Linux,使用替换项目列表在文件文件夹上查找替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!