10

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

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"

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. I also know the 'read' command but dont know how to use it in order a certain line.

Thanks in advance for the help.

user3206874
  • 795
  • 2
  • 7
  • 15
  • possible duplicate of [bash tool to get nth line from a file](http://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file) – tripleee Nov 21 '14 at 11:05

2 Answers2

28

Using head and tail

$ 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 -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.

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

  • input input file

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

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

Using awk

Perhaps an awk solution might look like

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

Thanks to Fredrik Pihl for the suggestion.

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
0

Perl has convenient support for this, too, and it's actually the most intuitive!

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.

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)

Marcus
  • 5,104
  • 2
  • 28
  • 24