微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Linux中替换多个文件中的文本字符串

有多种方法可以将多个文本中的一个文本替换为另一个文本.以下是几种方法

使用sed并查找:

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/'

请提供您自己的建议.

解决方法

我会用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_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_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])

对于单个搜索和替换一种类型文件中的一个字符串,使用find和sed的解决方案也不错.但是如果你想在一次通过中做很多处理,你可以编辑这个程序来扩展它,这将很容易(并且第一次可能是正确的).

原文地址:https://www.jb51.cc/linux/396825.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐