使用BASH、awk、sed或其他工具删除文件的前两行

39

我想删除一个文件的前两行,通过不将它们打印到另一个文件。我不需要什么高级的东西。这是我的 awk 尝试(失败了):

awk '{ (NR > 2) {print} }' myfile

这会抛出以下错误:

awk: { NR > 2 {print} }
awk:          ^ syntax error

例子:

'myfile' 的内容:

blah
blahsdfsj
1 
2
3
4

我希望得到的结果是什么:

1
2
3
4
4个回答

77

使用 tail 命令:

tail -n+3 file

来自手册页:

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

31

那么这样怎么样:

tail +3 file

或者

awk 'NR>2' file

或者

sed '1,2d' file

2
另一种sed变体:sed -n '3,$p' file - anubhava

26

你已经快成功了,尝试用这个方法代替:

awk 'NR > 2 { print }' myfile

awk是基于规则的,规则通常出现在要执行的语句块之前,并且不带花括号。

而且,正如Jaypal指出的那样,在awk中,如果您只想打印与规则匹配的行,则甚至可以省略动作,从而简化命令:

awk 'NR > 2' myfile

他也可以在括号前面加上一个 if,但是你的方法更好,因为它不会涉及每一行,只涉及已经匹配的行。 - Dan Fego
1
你甚至不需要 { print }。一种 awkish 的方式是 awk 'NR>2' myfile - jaypal singh

6

awk 是基于 pattern{action} 语句的。在你的情况下,patternNR>2,你想要执行的 actionprint。这个 action 也是 awk默认操作

因此,即使

awk 'NR>2{print}' filename

可以正常工作,你也可以缩短它为

awk 'NR>2' filename


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接