Command to get nth line of STDOUT

前端 未结 12 1745
闹比i
闹比i 2020-12-07 07:39

Is there any bash command that will let you get the nth line of STDOUT?

That is to say, something that would take this

$ ls -l
-rw-r--r--@ 1 root  wh         


        
相关标签:
12条回答
  • 2020-12-07 07:56

    Using sed, just for variety:

    ls -l | sed -n 2p
    

    Using this alternative, which looks more efficient since it stops reading the input when the required line is printed, may generate a SIGPIPE in the feeding process, which may in turn generate an unwanted error message:

    ls -l | sed -n -e '2{p;q}'
    

    I've seen that often enough that I usually use the first (which is easier to type, anyway), though ls is not a command that complains when it gets SIGPIPE.

    For a range of lines:

    ls -l | sed -n 2,4p
    

    For several ranges of lines:

    ls -l | sed -n -e 2,4p -e 20,30p
    ls -l | sed -n -e '2,4p;20,30p'
    
    0 讨论(0)
  • 2020-12-07 07:56

    Another poster suggested

    ls -l | head -2 | tail -1
    

    but if you pipe head into tail, it looks like everything up to line N is processed twice.

    Piping tail into head

    ls -l | tail -n +2 | head -n1
    

    would be more efficient?

    0 讨论(0)
  • 2020-12-07 07:58
    ls -l | head -2 | tail -1
    
    0 讨论(0)
  • 2020-12-07 08:02

    Is Perl easily available to you?

    $ perl -n -e 'if ($. == 7) { print; exit(0); }'
    

    Obviously substitute whatever number you want for 7.

    0 讨论(0)
  • 2020-12-07 08:04

    Alternative to the nice head / tail way:

    ls -al | awk 'NR==2'
    

    or

    ls -al | sed -n '2p'
    
    0 讨论(0)
  • 2020-12-07 08:04

    Hmm

    sed did not work in my case. I propose:

    for "odd" lines 1,3,5,7... ls |awk '0 == (NR+1) % 2'

    for "even" lines 2,4,6,8 ls |awk '0 == (NR) % 2'

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