unix - head AND tail of file

前端 未结 20 1202
误落风尘
误落风尘 2020-12-07 11:05

Say you have a txt file, what is the command to view the top 10 lines and bottom 10 lines of file simultaneously?

i.e. if the file is 200 lines long, then view lines

相关标签:
20条回答
  • 2020-12-07 11:49

    It took make a lot of time to end-up with this solution which, seems to be the only one that covered all use cases (so far):

    command | tee full.log | stdbuf -i0 -o0 -e0 awk -v offset=${MAX_LINES:-200} \
              '{
                   if (NR <= offset) print;
                   else {
                       a[NR] = $0;
                       delete a[NR-offset];
                       printf "." > "/dev/stderr"
                       }
               }
               END {
                 print "" > "/dev/stderr";
                 for(i=NR-offset+1 > offset ? NR-offset+1: offset+1 ;i<=NR;i++)
                 { print a[i]}
               }'
    

    Feature list:

    • live output for head (obviously that for tail is not possible)
    • no use of external files
    • progressbar one dot for each line after the MAX_LINES, very useful for long running tasks.
    • progressbar on stderr, assuring that the progress dots are separated from the head+tail (very handy if you want to pipe stdout)
    • avoids possible incorrect logging order due to buffering (stdbuf)
    • avoid duplicating output when total number of lines is smaller than head + tail.
    0 讨论(0)
  • 2020-12-07 11:50

    Consumes stdin, but simple and works for 99% of use cases

    head_and_tail

    #!/usr/bin/env bash
    COUNT=${1:-10}
    IT=$(cat /dev/stdin)
    echo "$IT" | head -n$COUNT
    echo "..."
    echo "$IT" | tail -n$COUNT
    

    example

    $ seq 100 | head_and_tail 4
    1
    2
    3
    4
    ...
    97
    98
    99
    100
    
    0 讨论(0)
提交回复
热议问题