Tuesday, April 1, 2008

How can get nth line from a file

  1. time head -5 emp.lst tail -1
    It has taken time for execution is
    real 0m0.004s
    user 0m0.001s
    sys 0m0.001s
    or
  2. awk 'NR==5' emp.lst
    It has taken time for execution is
    real 0m0.003s
    user 0m0.000s
    sys 0m0.002s
    or
  3. sed -n '5p' emp.lst
    It has taken time for execution is
    real 0m0.001s
    user 0m0.000s
    sys 0m0.001s
    or
  4. using some cute trick we can get this with cut command
    cut -d “
    “ -f 5 emp.lst
    # after -d press enter ,it means delimiter is newline
    It has taken time for execution is
    real 0m0.001s
    user 0m0.000s
    sys 0m0.001s

    Analysis: comparing above commands 'head' command taken maximum time
    because it pipes the output to tail command. piping consumes some
    time.
    Next “awk” command has taken greater time ,because 'awk' not only
    a command, it is a programing language too.

3 comments:

  1. Hi venu
    thank you very much
    keep this blog upto date
    and post new tricks

    ReplyDelete
  2. I am currently using exactly what you suggest in your sed example. My problem is that my file is quite large - almost 5 million lines. I also need certain blocks of lines, e.g. every other set of say 10 lines. So,My name is Nagaraj I'm working cabs in kochi I wrote a bash script for it, but it is taking a very long time. I am wondering if it is so, because although -n represses the output of the majority of the lines, it is still traversing them all. I don't know if this is true.

    ReplyDelete