unix - head AND tail of file

前端 未结 20 1284
误落风尘
误落风尘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 11:46

    For a pure stream (e.g. output from a command), you can use 'tee' to fork the stream and send one stream to head and one to tail. This requires using either the '>( list )' feature of bash (+ /dev/fd/N):

    ( COMMAND | tee /dev/fd/3 | head ) 3> >( tail )
    

    or using /dev/fd/N (or /dev/stderr) plus subshells with complicated redirection:

    ( ( seq 1 100 | tee /dev/fd/2 | head 1>&3 ) 2>&1 | tail ) 3>&1
    ( ( seq 1 100 | tee /dev/stderr | head 1>&3 ) 2>&1 | tail ) 3>&1
    

    (Neither of these will work in csh or tcsh.)

    For something with a little better control, you can use this perl command:

    COMMAND | perl -e 'my $size = 10; my @buf = (); while (<>) { print if $. <= $size; push(@buf, $_); if ( @buf > $size ) { shift(@buf); } } print "------\n"; print @buf;'
    

提交回复
热议问题