Bash tool to get nth line from a file

前端 未结 19 2073
刺人心
刺人心 2020-11-22 08:07

Is there a \"canonical\" way of doing that? I\'ve been using head -n | tail -1 which does the trick, but I\'ve been wondering if there\'s a Bash tool that speci

相关标签:
19条回答
  • 2020-11-22 09:09

    With awk it is pretty fast:

    awk 'NR == num_line' file
    

    When this is true, the default behaviour of awk is performed: {print $0}.


    Alternative versions

    If your file happens to be huge, you'd better exit after reading the required line. This way you save CPU time See time comparison at the end of the answer.

    awk 'NR == num_line {print; exit}' file
    

    If you want to give the line number from a bash variable you can use:

    awk 'NR == n' n=$num file
    awk -v n=$num 'NR == n' file   # equivalent
    

    See how much time is saved by using exit, specially if the line happens to be in the first part of the file:

    # Let's create a 10M lines file
    for ((i=0; i<100000; i++)); do echo "bla bla"; done > 100Klines
    for ((i=0; i<100; i++)); do cat 100Klines; done > 10Mlines
    
    $ time awk 'NR == 1234567 {print}' 10Mlines
    bla bla
    
    real    0m1.303s
    user    0m1.246s
    sys 0m0.042s
    $ time awk 'NR == 1234567 {print; exit}' 10Mlines
    bla bla
    
    real    0m0.198s
    user    0m0.178s
    sys 0m0.013s
    

    So the difference is 0.198s vs 1.303s, around 6x times faster.

    0 讨论(0)
提交回复
热议问题