unix - head AND tail of file

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

    the problem here is that stream-oriented programs don't know the length of the file in advance (because there might not be one, if it's a real stream).

    tools like tail buffer the last n lines seen and wait for the end of the stream, then print.

    if you want to do this in a single command (and have it work with any offset, and do not repeat lines if they overlap) you'll have to emulate this behaviour I mentioned.

    try this awk:

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

提交回复
热议问题