Command to get nth line of STDOUT

前端 未结 12 1743
闹比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:40

    You can use awk:

    ls -l | awk 'NR==2'
    

    Update

    The above code will not get what we want because of off-by-one error: the ls -l command's first line is the total line. For that, the following revised code will work:

    ls -l | awk 'NR==3'
    
    0 讨论(0)
  • 2020-12-07 07:41

    Try this sed version:

    ls -l | sed '2 ! d'
    

    It says "delete all the lines that aren't the second one".

    0 讨论(0)
  • 2020-12-07 07:44

    From sed1line:

    # print line number 52
    sed -n '52p'                 # method 1
    sed '52!d'                   # method 2
    sed '52q;d'                  # method 3, efficient on large files
    

    From awk1line:

    # print line number 52
    awk 'NR==52'
    awk 'NR==52 {print;exit}'          # more efficient on large files
    
    0 讨论(0)
  • 2020-12-07 07:50

    Yes, the most efficient way (as already pointed out by Jonathan Leffler) is to use sed with print & quit:

    set -o pipefail                        # cf. help set
    time -p ls -l | sed -n -e '2{p;q;}'    # only print the second line & quit (on Mac OS X)
    echo "$?: ${PIPESTATUS[*]}"            # cf. man bash | less -p 'PIPESTATUS'
    
    0 讨论(0)
  • 2020-12-07 07:50

    For more completeness..

    ls -l | (for ((x=0;x<2;x++)) ; do read ; done ; head -n1)
    

    Throw away lines until you get to the second, then print out the first line after that. So, it prints the 3rd line.

    If it's just the second line..

    ls -l | (read; head -n1)
    

    Put as many 'read's as necessary.

    0 讨论(0)
  • 2020-12-07 07:55

    For the sake of completeness ;-)

    shorter code

    find / | awk NR==3
    

    shorter life

    find / | awk 'NR==3 {print $0; exit}'
    
    0 讨论(0)
提交回复
热议问题