unix - 使用 grep 和 sed 将一个字符串替换为另一个字符串

标签 unix sed grep

我想用另一个文件中的字符串替换一个文件中的一个字符串。虽然我对这些命令没有经验,但我希望 grep 和 sed 的某种组合会做得最好。

让这变得更复杂的是我不知道这两个字符串是什么(我正在尝试自动替换文档中的版本号)。我确实知道在这两种情况下我正在寻找的字符串(例如“2.3.4”)前面都是“version:”

那么我可以说“在“version:”之后查找单词(或行的其余部分或任何可能的内容)(我们称之为 string1),并在另一个文件中执行相同的操作(给出 string2)并将字符串 string1 替换为 string2。

以下是一些示例文本文件:

文件1.txt

This is a file containing
the updated version number.
version: 2.3.4
here is a string with more info

文件2.txt

This is a configuration file
It could contain an old version number
version: 2.3.2
Please update this

因此 file2.txt 的预期输出将变为:

文件2.txt

This is a configuration file
It could contain an old version number
version: 2.3.4
Please update this

谢谢

最佳答案

假设您有一个支持 -i 选项的 sed

sed -i 's/version: .*/version: 1.2.3/' file1 file2 file3 ...

您可能想要调整正则表达式通配符; .* 匹配到行尾,而 [.0-9]* 匹配尽可能长的点和数字序列。您可能还希望允许周围空白的变化...但是由于这可能是该网站上前 10% 的常见问题解答之一,因此此时请查找类似的问题。

从 file1 获取替换字符串并将其应用于 file2、file3 等,类似于

new=$(sed -n 's/version: //p' file1)
# Use double quotes, not single, in order to expand $new
sed -i "s/version: [.0-9]*/version: $new/" file2 file3 ...

第一个 sed 调用将仅打印找到并删除“version:”的行(用空字符串替换)。据推测,该文件中只有一行这样的行。将输出通过管道传输到 head -n 1uniq 等,或者查找/创建更复杂的 sed 脚本。

您通常在文字字符串周围使用单引号,但由于您不希望在替换中使用文字 $new,因此我们使用双引号,这允许 shell 执行变量替换(以及引用字符串中的其他替换数量(我们在此不讨论)。

关于unix - 使用 grep 和 sed 将一个字符串替换为另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11536975/

相关文章:

bash - 在 mac bash 终端中使用 shell 命令时出现 "Illegal Byte sequence"错误

bash - sed 编辑 csv 文件中的特定列和行

grep - 需要有关另一个 grep 命令输出的 grep 帮助

linux - 在 unix 中批量重命名文件并回滚

c++ - 需要当前进程的 PID,getpid() 返回 -1

bash - sed:在文件最后一行的位置搜索和替换值

c - 如何在任何 C 函数开始之后和函数结束之前插入文本行?

python - 你如何在 Python 中搜索子进程输出的特定词?

c - 使用 execl 重定向 ls

regex - sed 命令不更新文本文件