如何从bash中的文本文件中读取第n行?

use*_*874 7 linux bash file

假设我有一个名为"demo.txt"的文本文件,如下所示:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Run Code Online (Sandbox Code Playgroud)

现在我想读一行,比如第2行,用一个看起来像这样的命令:

Line2 = read 2 "demo.txt"
Run Code Online (Sandbox Code Playgroud)

所以当我打印它时:

echo "$Line2"
Run Code Online (Sandbox Code Playgroud)

我去拿:

5 6 7 8
Run Code Online (Sandbox Code Playgroud)

我知道如何使用'sed'命令从文件中打印第n行,但不知道如何读取它.我也知道'读'命令,但不知道如何使用它来排序某一行.

在此先感谢您的帮助.

nu1*_*73R 17

使用headtail

$ head -2 inputFile | tail -1
5 6 7 8
Run Code Online (Sandbox Code Playgroud)

要么

一般化版本

$ line=2
$ head -"$line" input | tail -1
5 6 7 8
Run Code Online (Sandbox Code Playgroud)

使用sed

$ sed -n '2 p' input
5 6 7 8
$  sed -n "$line p" input
5 6 7 8
Run Code Online (Sandbox Code Playgroud)

它能做什么?

  • -n 抑制图案空间的正常打印.

  • '2 p'指定行号,2或($line更一般地说)p打印当前模式空间的命令

  • input 输入文件

编辑

要将输出转换为某个变量,请使用一些命令替换技术.

$ content=`sed -n "$line p" input`
$ echo $content
5 6 7 8
Run Code Online (Sandbox Code Playgroud)

要么

$ content=$(sed -n "$line p" input)
$ echo $content
5 6 7 8
Run Code Online (Sandbox Code Playgroud)

获取bash数组的输出

$ content= ( $(sed -n "$line p" input) )
$ echo ${content[0]}
5
$ echo ${content[1]}
6
Run Code Online (Sandbox Code Playgroud)

使用awk

也许awk解决方案可能看起来像

$  awk -v line=$line 'NR==line' input
5 6 7 8
Run Code Online (Sandbox Code Playgroud)

感谢Fredrik Pihl提出的建议.