unix - head AND tail of file

前端 未结 20 1205
误落风尘
误落风尘 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:32

    I have been looking for this solution for a while. Tried it myself with sed, but the problem with not knowing the length of file/stream beforehand was insurmountable. Of all the options available above, I like Camille Goudeseune's awk solution. He did make a note that his solution left extra blank lines in the output with a sufficiently small data set. Here I provide a modification of his solution that removes the extra lines.

    headtail() { awk -v offset="$1" '{ if (NR <= offset) print; else { a[NR] = $0; delete a[NR-offset] } } END { a_count=0; for (i in a) {a_count++}; for (i=NR-a_count+1; i<=NR; i++) print a[i] }' ; }
    
    0 讨论(0)
  • 2020-12-07 11:33
    sed -n "1,10p; $(( $(wc -l ${aFile} | grep -oE "^[[:digit:]]+")-9 )),\$p" "${aFile}"
    

    NOTE: The aFile variable contains the file's full path.

    0 讨论(0)
  • 2020-12-07 11:37

    ed is the standard text editor

    $ echo -e '1+10,$-10d\n%p' | ed -s file.txt
    
    0 讨论(0)
  • 2020-12-07 11:38

    First 10 lines of file.ext, then its last 10 lines:

    cat file.ext | head -10 && cat file.ext | tail -10

    Last 10 lines of the file, then the first 10:

    cat file.ext | tail -10 && cat file.ext | head -10

    You can then pipe the output elsewhere too:

    (cat file.ext | head -10 && cat file.ext | tail -10 ) | your_program

    0 讨论(0)
  • 2020-12-07 11:39

    Well, you can always chain them together. Like so, head fiename_foo && tail filename_foo. If that is not sufficient, you could write yourself a bash function in your .profile file or any login file that you use:

    head_and_tail() {
        head $1 && tail $1
    }
    

    And, later invoke it from your shell prompt: head_and_tail filename_foo.

    0 讨论(0)
  • 2020-12-07 11:40

    drawing on ideas above (tested bash & zsh)

    but using an alias 'hat' Head and Tails

    alias hat='(head -5 && echo "^^^------vvv" && tail -5) < '
    
    
    hat large.sql
    
    0 讨论(0)
提交回复
热议问题