代码之家  ›  专栏  ›  技术社区  ›  damon Curtis Snowden

在多个文件中查找/替换的最佳方法?

  •  36
  • damon Curtis Snowden  · 技术社区  · 16 年前

    最好的方法是什么?我不是命令行战士,但我想可能有一种方法可以使用grep和cat。

    我只想替换文件夹和子文件夹中出现的字符串。最好的方法是什么?如果这很重要的话,我正在运行Ubuntu。

    -D

    4 回复  |  直到 16 年前
        1
  •  36
  •   Paul Tomblin    10 年前
    find . -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g'
    

    第一部分是查找命令,用于查找要更改的文件。您可能需要适当地修改它。“xargs”命令获取找到的每个文件,并对其应用“sed”命令。“sed”命令获取“from”的每个实例,并将其替换为“to”。这是一个标准的正则表达式,请根据需要修改它。

    如果使用SVN,请小心。您的.svn目录也将被搜索和替换。您必须排除这些内容,例如:

    find . ! -regex ".*[/]\.svn[/]?.*" -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g'

    find . -name .svn -prune -o -type f -print0 | xargs -0 -n 1 sed -i -e 's/from/to/g'

        2
  •  37
  •   Sridhar Ratnakumar    12 年前

    正如保罗所说,首先要找到要编辑的文件,然后再编辑它们。使用find的另一种选择是使用gnu grep(Ubuntu上的默认值),例如:

    grep -r -l from . | xargs -0 -n 1 sed -i -e 's/from/to/g'
    

    http://petdance.com/ack/ )另外,如果您知道您只需要某种类型的文件,并且希望忽略版本控制目录中的内容。例如,如果只需要文本文件,

    ack -l --print0 --text from | xargs -0 -n 1 sed -i -e 's/from/to/g'
    # `from` here is an arbitrary commonly occurring keyword
    

    使用SED的另一种选择是使用Perl,它可以每个命令处理多个文件,例如,

    grep -r -l from . | xargs perl -pi.bak -e 's/from/to/g'
    

    这里,Perl被要求就地编辑,首先生成一个.bak文件。

    根据您的喜好,可以将管道的任何左侧和右侧组合在一起。

        3
  •  26
  •   doremi    9 年前

    我将为使用 Ag , The Silver Searcher 在多个文件上执行查找/替换操作。

    完整示例:

    ag -l "search string" | xargs sed -i '' -e 's/from/to/g'
    

    如果我们把它分解,我们得到的是:

    # returns a list of files containing matching string
    ag -l "search string"
    

    接下来,我们有:

    # consume the list of piped files and prepare to run foregoing command
    # for each file delimited by newline
    xargs
    

    最后,字符串替换命令:

    # -i '' means edit files in place and the '' means do not create a backup
    # -e 's/from/to/g' specifies the command to run, in this case,
    # global, search and replace
    
    sed -i '' -e 's/from/to/g'
    
        4
  •  3
  •   Bernhard E. Reiter    12 年前

    替代 sed 正在使用 rpl (例如,可从 http://rpl.sourceforge.net/ 或者您的GNU/Linux发行版),比如 rpl --recursive --verbose --whole-words 'F' 'A' grades/