替换同一文件夹中 200 多个文件中的相同文本

替换同一文件夹中 200 多个文件中的相同文本

我在 Ubuntu 22.04 上的一个文件夹中有 200 多个文件。我想在这些文件中搜索特定文本。如果找到该文本,则应将其替换为另一个文本。我该如何实现?

答案1

基本版本是:

sed --in-place 's/foo/bar/g' *

这将s搜索foo并将其更改为bar g本地。该--in-place标志会更改实际文件,因此请谨慎使用。如果添加后缀(--in-place=bak),则会生成扩展名为“bak”的备份文件。

如果遇到特殊字符(而且有很多),则需要对其进行转义。我无法比 Gilles 在 SO 上更好地解释这一点:https://unix.stackexchange.com/a/33005/10017


还有一个名为rpl(替换文件中的字符串)的工具可以使其更容易(使用:安装sudo apt install rpl),您可以使用它来执行以下操作:

rpl --dry-run 'foo' 'bar' '*/*.*'

上述命令将仅模拟(试运行)操作,因此它将显示文件将发生哪些更改,但不会应用这些更改。如果您对得到的结果感到满意,请运行不带标志的命令--dry-run

rpl 'foo' 'bar' '*/*.*'

答案2

尝试这个:

grep -rl 'your_old_text' /path/to/folder | xargs sed -i 's/your_old_text/your_new_text/g'  

答案3

perl...它具有文本搜索和替换语法s/SEARCH/REPLACEMENT/(其中SEARCH作为正则表达式处理,并REPLACEMENT作为“大部分”字符串处理)支持g全球化搜索和替换,它有一个-i地点文件编辑命令行选项如果使用的话,可以保存文件的备份,例如-i.bak.bak用作备份文件的扩展名,并且它可以在一次运行中处理多个文件,如下所示:

perl -i.bak -pe 's/SEARCH/REPLACEMENT/g' folder/*

示范:
$ mkdir folder
$
$
$ for i in {1..3}
  do 
    printf '%s\n' "Line1 in File${i} some SEARCH text and another SEARCH text." "Line2 in File${i} some SEARCH text and another SEARCH text." > folder/file"$i"
    done
$
$
$ head folder/*
==> folder/file1 <==
Line1 in File1 some SEARCH text and another SEARCH text.
Line2 in File1 some SEARCH text and another SEARCH text.

==> folder/file2 <==
Line1 in File2 some SEARCH text and another SEARCH text.
Line2 in File2 some SEARCH text and another SEARCH text.

==> folder/file3 <==
Line1 in File3 some SEARCH text and another SEARCH text.
Line2 in File3 some SEARCH text and another SEARCH text.
$
$
$ perl -i.bak -pe 's/SEARCH/REPLACEMENT/g' folder/*
$
$
$ head folder/*
==> folder/file1 <==
Line1 in File1 some REPLACEMENT text and another REPLACEMENT text.
Line2 in File1 some REPLACEMENT text and another REPLACEMENT text.

==> folder/file1.bak <==
Line1 in File1 some SEARCH text and another SEARCH text.
Line2 in File1 some SEARCH text and another SEARCH text.

==> folder/file2 <==
Line1 in File2 some REPLACEMENT text and another REPLACEMENT text.
Line2 in File2 some REPLACEMENT text and another REPLACEMENT text.

==> folder/file2.bak <==
Line1 in File2 some SEARCH text and another SEARCH text.
Line2 in File2 some SEARCH text and another SEARCH text.

==> folder/file3 <==
Line1 in File3 some REPLACEMENT text and another REPLACEMENT text.
Line2 in File3 some REPLACEMENT text and another REPLACEMENT text.

==> folder/file3.bak <==
Line1 in File3 some SEARCH text and another SEARCH text.
Line2 in File3 some SEARCH text and another SEARCH text.

答案4

如果您想采用 GUI 方式,请安装具有“在所有文件中替换”功能的 IDE。

我知道的是 Jetbrains 的 IntelliJ 和 Rider。

其他人也应该这样做,因为替换项目所有文件中的文本是一项常规的重构任务。

IDE 的优点是您可以手动跳过替换。

相关内容