0

How do i extract the text present in the 7th line of a file using shell script For eg., I have sumthing like,

abc
def
ghi
jkl
mno
pqr
stu

I need to print the text stu.

Can sumbdy help on this. Pls...

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • possible duplicate of [print every nth line into a row using gawk](http://stackoverflow.com/questions/9968916/print-every-nth-line-into-a-row-using-gawk) – l0b0 Jun 25 '13 at 12:53
  • 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) – doubleDown Jun 25 '13 at 22:49

2 Answers2

3

You can make it with awk:

awk 'NR==7' file

as NR refers to number of line.

Also in sed:

sed -n '7p' file

Update And even better (thanks pixelbeat)

sed -n '7{p;q}' file

Test to see how better is the second option:

Let's fill a file with 1,000,000 lines:

$ for i in {1..1000000}; do echo $i>>a; done

Now let's compare the time used by each sed:

$ time sed -n '3p' a
3

real    0m0.098s
user    0m0.084s
sys     0m0.008s
$ time sed -n '3{p;q}' a
3

real    0m0.012s
user    0m0.000s
sys     0m0.008s

Which is 8 times faster!

$ echo "0.098 / 0.012" | bc
8
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
0

In addition to awk, there are many other utilities that can be composed to do this. Here are a few more:

head and tail

head -n 7 file | tail -n 1

perl

perl -ne 'print if $.==7' file

ruby is actually identical to the perl

ruby -ne 'print if $.==7' file

There is probably a shorter way, here it is in python:

python -c "import sys; x=[l for l in sys.stdin]; sys.stdout.write(x[6])" < x
Kyle Burton
  • 26,788
  • 9
  • 50
  • 60
  • 1
    You missed `java` and `php` :) I think it is quite useful to have such broad options, although having tag:shell i don't think it is that necessary. – fedorqui Jun 25 '13 at 12:16
  • Java isn't very good at shell scripting (certainly not these kinds of 1-liners). PHP isn't installed on my systems and I don't have much experience using it. These are the things I typically use from my shell scripts. Just offering options. :) Regards – Kyle Burton Jun 25 '13 at 12:20