使用 sed 进行文本替换
在这一步中,我们将探索如何使用 sed 命令进行更高级的文本替换。
首先,让我们创建一个包含多个 "old" 单词的新示例文件:
echo "This is an old text. Replace the old text with new text." > sample.txt
替换所有匹配的单词
要替换所有匹配的单词,可以使用全局标志 g:
sed 's/old/new/g' sample.txt
示例输出:
This is an new text. Replace the new text with new text.
仅替换第一个匹配项
要仅替换第一个匹配项,可以省略全局标志 g:
sed 's/old/new/' sample.txt
示例输出:
This is an new text. Replace the old text with new text.
在特定行中替换文本
要在特定行中替换文本,可以在 s 命令前指定行号:
sed '1s/old/new/' sample.txt
示例输出:
This is an new text. Replace the old text with new text.
使用正则表达式替换
sed 还支持正则表达式。要使用正则表达式替换文本,可以使用 \1 语法引用捕获组:
sed 's/\(This.*\)old\(.*\)/\1new\2/' sample.txt
示例输出:
This is an new text. Replace the new text with new text.
在多个文件中替换文本
要在多个文件中替换文本,可以将文件名作为参数传递给 sed 命令:
sed 's/old/new/g' sample.txt another_file.txt
这将在 sample.txt 和 another_file.txt 中执行文本替换。
在下一步中,我们将学习如何使用 sed 命令编辑多个文件。