在 Linux 中使用 SED 取消注释文件中的行

在本教程中,您将学习如何在 Linux 中使用 SED 取消注释文件中的行。 根据 人 sed, “Sed 是一个流编辑器。 流编辑器用于对输入流(文件或来自管道的输入)执行基本的文本转换。 虽然在某些方面类似于允许脚本化编辑的编辑器(例如 ed),但 sed 仅通过对输入进行一次传递即可工作,因此效率更高。 但是 sed 在管道中过滤文本的能力使其与其他类型的编辑器特别不同”。

在 Linux 中使用 SED 取消注释文件中的行

因此,无需打开文件并取消对特定行的注释,只需在命令行中使用 sed 取消对该特定行的注释即可节省一些时间。

为了演示如何在 linux 中使用 sed 取消注释文件中的行,例如,您有一个包含以下内容的文件;

cat /tmp/lines
This is line1 #This is line2 This is line3 #line4 This is line5 This is line6 #My line7 This is line8 This is line9 This is line10 This is line11 Your is line12 This is line13 This is line14 #Their line15 This is line16 This is line17 #This is line18 This is line19 This is line20

许多行已被注释(# 放在开头)。

在 Linux 中使用 SED 取消注释具有特定模式的行

要使用 sed 取消注释具有特定模式的特定行,您只需运行以下命令;

sed '/pattern/s/^#//' -i file

上面只会对第一个匹配行进行注释。

更换 图案匹配关键字 线和 文件 带有特定的文件名。

如果文件包含与模式匹配的多行,并且所有行都被注释,并且想要全部取消注释,请确保使用全局运行 sed 命令 G 手术;

sed '/pattern/s/^#//g' -i file

例如,用模式取消注释一行 这个,然后运行;

sed '/This/s/^#//' -i /tmp/lines

如果您想在试运行模式下运行 set 而不实际将更改应用于内联文件,则省略选项 -i.

上面的命令只会取消注释与指定模式匹配的第一个注释行,在这种情况下是第二行, #这是第2行.

cat /tmp/lines
This is line1 This is line2 This is line3 #line4 This is line5 This is line6 #My line7 This is line8 This is line9 This is line10 This is line11 Your is line12 This is line13 This is line14 #Their line15 This is line16 This is line17 #This is line18 This is line19 This is line20

要取消注释文件中与模式匹配的所有注释行, 这个,然后运行;

sed '/This/s/^#//g' -i /tmp/lines

如果要在应用更改之前创建原始文件的备份,请使用该选项 -i. 代替 -一世 在哪里 在后面、原始、旧或任何要附加到备份文件的前缀。

sed '/This/s/^#//g' -i.bak /tmp/lines

在 Linux 中使用 SED 取消注释文件中的特定行号

也可以使用 sed 来取消对文件中特定行号的注释。

在文件中,在使用vim编辑器时,可以通过按显示行号 ESC键, 并进入, :设置号码;

所以举个例子,你想取消注释文件中的第 4 行,然后按如下方式运行 sed;

sed '4s/^#//' /tmp/lines
This is line1 This is line2 This is line3 line4 This is line5 This is line6 #My line7 ...

要应用文件中的更改,请使用选项 -一世 如上所示。

取消注释多行 (线的范围),然后您可以在 sed 命令中指定开始的行号和结束的行号;

sed '$LINESTART,$LINEENDs/^#//' file

例如,要取消注释从第 4 行到第 7 行的行,然后;

sed '4,7s/^#//' file

如果这些行有一些标识,以便它们以制表符或空格开头,例如;

This is line1 	#This is line2 This is line3     #line4 This is line5 This is line6

然后你就可以跑了;

sed '1,5s/.*#//' /tmp/lines

这将删除 #、空格或制表符。 示例结果。

This is line1 This is line2 This is line3 line4 This is line5 This is line6 #My line7

所以为了保持标识,那么你可以简单地删除 #;

sed '1,5s/#//' /tmp/lines

样品结果;

This is line1 	This is line2 This is line3     line4 This is line5 This is line6 #My line7

标识被保留。

这标志着我们关于如何在 Linux 中使用 SED 取消注释文件中的行的教程的结束。

如果您有更多示例,请随时发表评论。

如何在vim中复制粘贴行

在 Linux 中对 resolv.conf 进行永久 DNS 更改

在 Linux 中使用 du 命令检查目录使用情况

如何在 Linux 中使用 htop 命令