简体   繁体   English

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

[英]How to read n-th line from a text file in bash?

Say I have a text file called "demo.txt" who looks like this:假设我有一个名为“demo.txt”的文本文件,如下所示:

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

Now I want to read a certain line, say line 2, with a command which will look something like this:现在我想读取某一行,比如第 2 行,其命令如下所示:

Line2 = read 2 "demo.txt"

So when I'll print it:所以当我打印它时:

echo "$Line2"

I'll get:我去拿:

5 6 7 8

I know how to use 'sed' command in order to print a n-th line from a file, but not how to read it.我知道如何使用“sed”命令从文件中打印第 n 行,但不知道如何读取它。 I also know the 'read' command but dont know how to use it in order a certain line.我也知道“读取”命令,但不知道如何在某行中使用它。

Thanks in advance for the help.在此先感谢您的帮助。

Using head and tail 使用headtail

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

OR 要么

a generalized version 一般化版本

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

Using sed 使用sed

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

What it does? 它能做什么?

  • -n suppresses normal printing of pattern space. -n禁止正常打印图案空间。

  • '2 p' specifies the line number, 2 or ( $line for more general), p commands to print the current patternspace '2 p'指定行号, 2或( $line为更一般), p命令打印当前模式空间

  • input input file input输入文件

Edit 编辑

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

To obtain the output to a bash array 获取bash数组的输出

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

Using awk 使用awk

Perhaps an awk solution might look like 也许awk解决方案可能看起来像

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

Thanks to Fredrik Pihl for the suggestion. 感谢Fredrik Pihl提出的建议。

Perl has convenient support for this, too, and it's actually the most intuitive! Perl 对此也有方便的支持,而且它实际上是最直观的!

The flip-flop operator can be used with line numbers:触发器运算符可以与行号一起使用:

$ printf "0\n1\n2\n3\n4" | perl -ne 'printf if 2 .. 4'
1
2
3

Note that it's 1-based.请注意,它是基于 1 的。

You can also mix regular expressions:您还可以混合使用正则表达式:

$ printf "0\n1\nfoo\n3\n4" | perl -ne 'printf if /foo/ .. -1'
foo
3
4

( -1 refers to the last line) -1指最后一行)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM