什么是从文件中使用awk删除第1次和最后一行的最简单的方法? [英] what is the easiest way to remove 1st and last line from file with awk?
问题描述
我学习的awk / GAWK。所以最近我试着去解决任何问题,以获得更多的实践机会。
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,
如何删除文件第一和最后一行的
"how to remove first and last line from file"
。我知道, sed的'1D $ D'文件
会工作。还头/尾
工作过,即使表现不佳。我告诉他SED之一,他是幸福的。
. I know that sed '1d;$d' file
would work. also head/tail
works too even if the poor performance. I told him the sed one, he was happy.
后来,我试图写一个awk单行:到目前为止,我得到的是:
Later, I was trying to wrote an awk one-liner: so far what I got is:
awk 'NR>1{a[++k]=$0}END{for(i=1;i<k;i++)print a[i]}'
这将存储阵列中的整个文件只跳过最后一行。我觉得应该有这样做更容易(或更好)的方式。
This will store whole file in array just to skip the last line. I feel that there should be an easier(or better) way to do that..
(如果没有更简单或更快或者更好的办法,我会删除这个问题)
(if there is no easier or faster or better way, I would remove the question)
感谢您。
推荐答案
这是卓有成效的:
awk 'NR>2 {print l} {l=$0}'
AWK
执行行动打印→
只有当NR> 2(也就是说,所有线路上,但第一2)。结果
所有线路上,它设置变量→
当前行。结果
因此,当 AWK
读取第三行,它打印2号线(这是保存在→
)。结果
当它读取的最后一行(第n行)它输出线n-1个的内容。结果,
净效果是线2至n-1的打印
awk
executes the action print l
only when NR > 2 (that is, on all lines but the first 2).
On all lines, it sets the variable l
to the current line.
So when awk
reads the third line, it prints line 2 (which was stored in l
).
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.
这篇关于什么是从文件中使用awk删除第1次和最后一行的最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!