What is the easiest way to remove 1st and last line from file with awk?

前端 未结 3 359
遥遥无期
遥遥无期 2020-12-31 00:07

I am learning awk/gawk. So recently I just try to solve any problem with it to gain more practice opportunities.

My coworker asked a question yesterday,

相关标签:
3条回答
  • 2020-12-31 00:20

    Let me suggest another solution. In case if you need custom N for top and bottom lines you can use tail and head commands:

    awk '{print $1}'  | head -n -1 | tail -n+2
    

    head -n -1 - removes last line

    tail -n+2 - starts output from second line (removes 1 line)

    Following command will remove 3 lines from top and bottom:

    awk '{print $1}'  | head -n -3 | tail -n +4
    

    Actually we don't even need awk here:

    more | head -n -1 | tail -n +2
    

    or

    cat | head -n -1 | tail -n +2
    

    Thanks to Igor Fobia for comment!

    0 讨论(0)
  • 2020-12-31 00:21

    This does the trick:

    awk 'NR>2 {print last} {last=$0}'
    

    awk executes the action print last only when NR > 2 (that is, on all lines but the first 2). On all lines, it sets the variable last to the current line. So when awk reads the third line, it prints line 2 (which was stored in last). When it reads the last line (line n) it prints the content of line n-1. The net effect is that lines 2 through n-1 are printed.

    0 讨论(0)
  • 2020-12-31 00:27

    Here is another way, but it required gawk function length:

    awk '{firstline=2; cuttail=1; l[NR]=$0} END {for (i=firstline; i<=length(l)-cuttail; i++) print l[i]}'
    
    0 讨论(0)
提交回复
热议问题