如何从bash中的文本文件中读取第n行? [英] How to read n-th line from a text file in bash?

查看:1417
本文介绍了如何从bash中的文本文件中读取第n行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个名为"demo.txt"的文本文件,它看起来像这样:

Say I have a text file called "demo.txt" who looks like this:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

现在,我想使用一条看起来像这样的命令来读取特定的一行,例如第2行:

Now I want to read a certain line, say line 2, with a command which will look something like this:

Line2 = read 2 "demo.txt"

所以当我打印它时:

echo "$Line2"

我会得到:

5 6 7 8

我知道如何使用'sed'命令从文件中打印第n行,但不知道如何读取.我也知道'read'命令,但是不知道如何在特定行中使用它.

I know how to use 'sed' command in order to print a n-th line from a file, but not how to read it. I also know the 'read' command but dont know how to use it in order a certain line.

预先感谢您的帮助.

推荐答案

使用headtail

Using head and tail

$ head -2 inputFile | tail -1
5 6 7 8

OR

通用版本

$ line=2
$ head -"$line" input | tail -1
5 6 7 8

使用sed

$ sed -n '2 p' input
5 6 7 8
$  sed -n "$line p" input
5 6 7 8

它做什么?

  • -n禁止正常打印图案空间.

  • -n suppresses normal printing of pattern space.

'2 p'指定行号,2或($line用于更常规),p命令以打印当前模式空间

'2 p' specifies the line number, 2 or ($line for more general), p commands to print the current patternspace

input输入文件

修改

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

To get the output to some variable use some command substitution techniques.

$ content=`sed -n "$line p" input`
$ echo $content
5 6 7 8

OR

$ content=$(sed -n "$line p" input)
$ echo $content
5 6 7 8

获取bash数组的输出

To obtain the output to a bash array

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

使用awk

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

Perhaps an awk solution might look like

$  awk -v line=$line 'NR==line' input
5 6 7 8

感谢弗雷德里克·皮尔(Fredrik Pihl)的建议.

Thanks to Fredrik Pihl for the suggestion.

这篇关于如何从bash中的文本文件中读取第n行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆