unix - head AND tail of file

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

    To handle pipes (streams) as well as files, add this to your .bashrc or .profile file:

    headtail() { awk -v offset="$1" '{ if (NR <= offset) print; else { a[NR] = $0; delete a[NR-offset] } } END { for (i=NR-offset+1; i<=NR; i++) print a[i] }' ; }
    

    Then you can not only

    headtail 10 < file.txt
    

    but also

    a.out | headtail 10
    

    (This still appends spurious blank lines when 10 exceeds the input's length, unlike plain old a.out | (head; tail). Thank you, previous answerers.)

    Note: headtail 10, not headtail -10.

提交回复
热议问题