如何在 Linux 命令行中找到文件中的第 n 行? 如何将行号 x 显示到行号 y?
在 Linux 中,有几种方法可以达到相同的结果。 从文件中打印特定行也不例外。
要显示第 13 行,可以使用 head 和 tail 的组合:
head -13 file_name | tail +13
或者,您可以使用 sed 命令:
sed -n '13p' file.txt
要显示从 20 到 25 的行号,可以像这样组合 head 和 tail 命令:
head -25 file_name | tail +20
或者,您可以像这样使用 sed 命令:
sed -n '20,25p' lines.txt
接下来是每个命令的详细说明。 我还将展示为此目的使用 awk 命令。
使用 head 和 tail 命令显示特定行
这是我最喜欢的显示选择线的方式。 我发现它更容易记住和使用。
打印单个特定行
在以下函数的行号 x 中使用 head 和 tail 命令的组合:
head -x file_name | tail +x
您可以将 x 替换为要显示的行号。 因此,假设您要显示文件的第 13 行。
[email protected]:~$ head -13 lines.txt | tail +13
This is line number 13
解释: 你可能已经知道 head 命令从文件的开头获取行,而 tail 命令从末尾获取行。
命令的“head -x”部分将获取文件的前 x 行。 然后它将这个输出重定向到tail命令。 tail 命令将显示从行号 x 开始的所有行。
很明显,如果从顶部取 13 行,则从第 13 行到末尾的行将是第 13 行。 这就是这个命令背后的逻辑。
打印特定范围的行
现在让我们结合使用 head 和 tail 命令来显示多行。
假设您要显示从 x 到 y 的所有行。 这还包括第 x 行和第 y 行:
head -y lines.txt | tail +x
让我们来一个实用的 example. 假设您要打印从第 20 行到第 25 行的所有行:
[email protected]:~$ head -25 lines.txt | tail +20
This is line number 20
This is line number 21
This is line number 22
This is line number 23
This is line number 24
This is line number 25
使用 SED 显示特定行
强大的 sed 命令提供了几种打印特定行的方法。
为了 example要显示第 10 行,可以按以下方式使用 sed:
sed -n '10p' file.txt
-n 禁止输出,而 p 命令打印特定行。 阅读此详细的 SED 指南以详细了解和了解它。
要显示从行号 x 到行号 y 的所有行,请使用以下命令:
[email protected]:~$ sed -n '3,7p' lines.txt
This is line number 3
This is line number 4
This is line number 5
This is line number 6
This is line number 7
使用 AWK 打印文件中的特定行
awk 命令可能看起来很复杂,而且肯定会涉及到学习曲线。 但与 sed 一样,awk 在编辑和操作文件内容方面也非常强大。
[email protected]:~$ awk 'NR==5' lines.txt
This is line number 5
NR 表示“当前记录号”。 请阅读我们详细的 AWK 命令指南以获取更多信息。
要显示从 x 到 y 的所有行,可以按以下方式使用 awk 命令:
[email protected]:~$ awk 'NR>=20 && NR<=25' lines.txt
This is line number 20
This is line number 21
This is line number 22
This is line number 23
This is line number 24
This is line number 25
它遵循类似于大多数编程语言的语法。
我希望这篇快速文章可以帮助您在 Linux 命令行中显示文件的特定行。 如果您知道为此目的的其他技巧,请在评论部分与我们其他人分享。