温馨提示×

linux如何替换文件内容

沐橙
7742
2021-06-08 16:07:03
栏目: 智能运维

linux中替换文件内容的方法:在linux终端可使用sed命令来替换文件内容;sed语法格式为:“sed -i [替换格式] [文件名]”,该语法中的替换格式为:“'s###'  --->  's#原内容##' ---> 's#原内容#替换后内容#'”;例如需要将每个首行world单词替换为World时,使用命令“sed -i 's#world#World#' testRep.txt”。

linux如何替换文件内容

具体步骤如下:

1、打开linux虚拟机,在桌面空白处右键 -- 打开终端。

linux如何替换文件内容

2、在终端使用vi编辑器创建一个‘testRep.txt’文件,并在文件写内容如下:

hello world

hello world

hello world world

保存退出。

linux如何替换文件内容

3、在终端替换文本内容需要使用sed命令,格式如下:

sed -i [替换格式] [文件名]

替换格式为:

's###'  --->  's#原内容##' ---> 's#原内容#替换后内容#'

例如替换每行首个world单词为World时使用命令:

sed -i 's#world#World#' testRep.txt

替换完成后,查看testRep.txt内容如下图所示,每行首个world变成了World。

linux如何替换文件内容

指定行号替换首个匹配内容在替换格式的最前面加行号即可,格式为:

sed -i '行号s#原内容#替换后内容#' 文件名

例如替换第2行的首个World为world,使用命令:

sed -i '2s#World#world#' testRep.txt

替换完成后,查看testRep.txt内容如下图所示,第2行首个World变成了world。

linux如何替换文件内容

如果不指定行号,默认就是每行,不指定行号指定列号替换匹配内容,格式为:

sed -i 's#原内容#替换后内容#列号' 文件名

例如替换每行第1个的World为world,使用命令:

sed -i 's#World#world#1' testRep.txt

替换完成后,查看testRep.txt内容如下图所示,每行第1个World变成了world。实际列号就是指出现的第几次,而不是所处的列。

linux如何替换文件内容

替换全部匹配内容,需要在上一步的替换格式后加g,例如替换所有的world为World,使用命令:

sed -i 's#world#World#g' testRep.txt

替换完成后,查看testRep.txt内容如下图所示,所有的world都变成了World。

linux如何替换文件内容

替换行号和列号可以同时使用,例如替换第3行第2个World为world,使用命令:

sed -i '3s#World#world#2' testRep.txt

替换完成后,查看testRep.txt内容如下图所示,第3行第2个World都变成了world。

linux如何替换文件内容

0