What's the opposite of head? I want all but the first N lines of a file

前端 未结 8 674
时光说笑
时光说笑 2020-12-07 19:55

Given a text file of unknown length, how can I read, for example all but the first 2 lines of the file? I know tail will give me the last N lines, but

相关标签:
8条回答
  • 2020-12-07 19:58

    Try sed 1,2d. Replace 2 as needed.

    0 讨论(0)
  • 2020-12-07 20:01

    tail --help gives the following:

      -n, --lines=K            output the last K lines, instead of the last 10;
                               or use -n +K to output lines starting with the Kth
    

    So to filter out the first 2 lines, -n +3 should give you the output you are looking for (start from 3rd).

    0 讨论(0)
  • 2020-12-07 20:10

    Assuming your version of tail supports it, you can specify starting the tail after X lines. In your case, you'd do 2+1.

    tail -n +3
    
    [mdemaria@oblivion ~]$ tail -n +3 stack_overflow.txt
    CCCC
    DDDD
    EEEE
    
    0 讨论(0)
  • 2020-12-07 20:10

    I really don't know how to do it from just tail or head but with the help of wc -l (line count) and bash expression, you can achieve that.

    tail -$(( $( wc -l $FILE | grep -Eo '[0-9]+' ) - 2 )) $FILE

    Hope this helps.

    0 讨论(0)
  • 2020-12-07 20:16

    Use this, supposing the first sample is called sample1.dat then tail --lines=3 sample1.dat which would print all lines from the 3rd line to the last line.

    For the second sample, again suppose it is called sample2.dat it would be tail --lines=-1 sample2.dat which would print the last line...

    0 讨论(0)
  • 2020-12-07 20:21

    using awk to get all but the last 2 line

    awk 'FNR==NR{n=FNR}FNR<=n-3{print}' file file
    

    awk to get all but the first 2 lines

    awk 'NR>2' file
    

    OR you can use more

    more +2 file
    

    or just bash

    #!/bin/bash
    
    i=0
    while read -r line
    do
      [[ $i > 1 ]] && echo "$line"
      ((i++))
    done <"file"
    
    0 讨论(0)
提交回复
热议问题