unix - head AND tail of file

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

    Why not to use sed for this task?

    sed -n -e 1,+9p -e 190,+9p textfile.txt

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

    To print the first 10 and last 10 lines of a file, you could try this:

    cat <(head -n10 file.txt) <(tail -n10 file.txt) | less

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

    head -10 file.txt; tail -10 file.txt

    Other than that, you'll need to write your own program / script.

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

    Based on J.F. Sebastian's comment:

    cat file | { tee >(head >&3; cat >/dev/null) | tail; } 3>&1
    

    This way you can process first line and the rest differently in one pipe, which is useful for working with CSV data:

    { echo N; seq 3;} | { tee >(head -n1 | sed 's/$/*2/' >&3; cat >/dev/null) | tail -n+2 | awk '{print $1*2}'; } 3>&1
    
    N*2
    2
    4
    6
    
    0 讨论(0)
  • 2020-12-07 11:31

    You can simply:

    (head; tail) < file.txt
    

    And if you need to uses pipes for some reason then like this:

    cat file.txt | (head; tail)
    

    Note: will print duplicated lines if number of lines in file.txt is smaller than default lines of head + default lines of tail.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题