有许多方法可以用多个文件中的另一个replace一个文本string。 以下是几种方法:
使用sed并find:
sed 's/oldstring/newstring/' "$1" > "$1".new && find -iname "*.new" | sed 's/.new//' | sh
使用grep和sed:
grep -rl oldstring . | xargs sed -i -e 's/oldstring/newstring/'
使用grep和perl:
grep -rl oldstring . | xargs perl -pi~ -e 's/oldstring/newstring/'
请提供您自己的build议。
我会用这个Python。 将所有这些代码放到一个名为mass_replace和“ chmod +x mass_replace ”的文件中:
#!/usr/bin/python import os import re import sys def file_replace(fname, s_before, s_after): out_fname = fname + ".tmp" out = open(out_fname, "w") for line in open(fname): out.write(re.sub(s_before, s_after, line)) out.close() os.rename(out_fname, fname) def mass_replace(dir_name, s_before, s_after): for dirpath, dirnames, filenames in os.walk(dir_name): for fname in filenames: f = fname.lower() # example: limit replace to .txt, .c, and .h files if f.endswith(".txt") or f.endswith(".c") or f.endswith(".h"): f = os.path.join(dirpath, fname) file_replace(f, s_before, s_after) if len(sys.argv) != 4: u = "Usage: mass_replace <dir_name> <string_before> <string_after>\n" sys.stderr.write(u) sys.exit(1) mass_replace(sys.argv[1], sys.argv[2], sys.argv[3])
对于一个文件中单个search和replace一个string,find和sed的解决scheme并不错。 但是如果你想一次完成大量的处理,你可以编辑这个程序来扩展它,这很容易(第一次可能是正确的)。
使用GNU find,xargs和sed是这样的:
find -name '*.txt' -o -name '*.html' -print0 | xargs -0 -P 1 -n 10 sed --in-place 's/oldstring/newstring/g'
根据需要调整-P和-n参数。 /g是需要的,这样一行中的每一次出现都被replace,而不仅仅是第一次出现(如果我没有记错的话, g代表全局 )。 您也可以将值传递到--in-place以进行备份。
我喜欢perl的就地过滤配方。
perl -pi.bak -e's / from / to /'file1 file2 ...
在上下文中…
% echo -e 'foo\ngoo\nboo' >test % perl -pi.bak -e 's/goo/ber/' test % diff -u test.bak test --- test.bak 2010-01-06 05:43:53.072335686 -0800 +++ test 2010-01-06 05:44:03.751585440 -0800 @@ -1,3 +1,3 @@ foo -goo +ber boo
这里是修剪的快速参考perl咒语使用…
% perl --help Usage: perl [switches] [--] [programfile] [arguments] -e program one line of program (several -e's allowed, omit programfile) -i[extension] edit <> files in place (makes backup if extension supplied) -n assume "while (<>) { ... }" loop around program -p assume loop like -n but print line also, like sed
假设文件列表不是一英里长,您不需要使用xargs,因为sed可以在命令行上处理多个文件:
sed -i -e 's/oldstring/newstring/' `grep -rl oldstring .`
如果用“/”字符replaceurl,请小心。
如何做到这一点的一个例子:
sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"
摘自: http : //www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html
感谢大家的一些伟大的答案! 这是超级有用的。
由于我没有数百个文件来replace行,所以我使用了一个do循环,如下所示:
for R in 1 2 3 4 5; do sed -i -e 's/oldstring/newstring/' file$R; done
希望有所帮助!