在 Bash 中从文件中删除行
作者:迹忆客
最近更新:2023/05/30
浏览次数:
在 Bash 脚本中,有几种方法可以从文件中删除一行。 本文将讨论从文件中删除不必要行的不同方法。
假设我们有一个名为 Test.txt 的文本文件,其内容如下。
This is the first line.
This is the second line.
This is the third line.
This is the fourth line.
使用 tail 删除文本文件的一行
我们可以使用 Bash 中的内置关键字 tail 从我们的文件中删除不需要的行。
命令:
$ tail -n +2 Test.txt
-n +2
将打印文件中除第一行以外的所有内容。 -n +1
将打印整个文件。
+
号反转参数并指示 tail 打印所有内容。
输出:
This is the second line.
This is the third line.
This is the fourth line.
使用 sed 删除一行文本文件
Bash 中的另一个内置命令名为 sed,它是一个内置的 Linux 工具,主要用于文本操作。 命令的完整形式是 Stream editor,因为此关键字采用流形式的文本并执行大量操作。
在下面的示例中,我们将从文件中删除第一行。
命令:
$ sed '1d' Test.txt
'1d'
指示 sed 命令在第一行执行删除操作。
输出:
This is the second line.
This is the third line.
This is the fourth line.
使用 awk 删除一行文本文件
在下面的示例中,我们将使用 awk
从文件中删除第一行。
命令:
awk 'NR>1' Test.txt
'NR>1'
表示行号大于 1。它将只显示第一行之后的行。
输出:
This is the second line.
This is the third line.
This is the fourth line.
总结
我们分享了三种从文件中删除一行的不同方法,您可以根据需要选择一种。 请注意,本文中使用的所有代码都是用 Bash 编写的,并且只会在 Linux Shell 环境中执行。
相关文章
在 Bash 中运行 find -exec 命令
发布时间:2024/03/14 浏览次数:127 分类:操作系统
-
本文将演示如何使用 find 命令的 -exec 参数来使用 find 命令定位文件中的任何文本。