使用 BASH 或 awk 或 sed 或其他方法删除文件的前两行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8857705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:28:42  来源:igfitidea点击:

Deleting the first two lines of a file using BASH or awk or sed or whatever

bashawksedlines

提问by Amit

I'm trying to delete the first two lines of a file by just not printing it to another file. I'm not looking for something fancy. Here's my (failed) attempt at awk:

我试图通过不将文件打印到另一个文件来删除文件的前两行。我不是在寻找花哨的东西。这是我对 awk 的(失败)尝试:

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

That throws out the following error:

这会抛出以下错误:

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

Example:

例子:

contents of 'myfile':

“我的文件”的内容:

blah
blahsdfsj
1 
2
3
4

What I want the result to be:

我想要的结果是:

1
2
3
4

回答by RobS

Use tail:

使用尾巴:

tail -n+3 file

from the man page:

从手册页:

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

回答by anubhava

How about:

怎么样:

tail +3 file

OR

或者

awk 'NR>2' file

OR

或者

sed '1,2d' file

回答by Chris J

You're nearly there. Try this instead:

你快到了。试试这个:

awk 'NR > 2 { print }' myfile

awk is rule based, and the rule appears bare (i.e., without braces) before the block it woud execute if it passes.

awk 是基于规则的,并且规则在它通过时将执行的块之前显示为裸露的(即,没有大括号)。

Also as Jaypal has pointed out, in awk if all you want to do is print the line that matches the rules you can even omit the action, thus simplifying the command to:

同样正如 Jaypal 所指出的,在 awk 中,如果您只想打印与规​​则匹配的行,您甚至可以省略该操作,从而将命令简化为:

awk 'NR > 2' myfile

回答by jaypal singh

awkis based on pattern{action}statements. In your case, the patternis NR>2and the actionyou want to perform is print. This actionis also the default actionof awk.

awk是基于pattern{action}陈述。在您的情况下,patternisNR>2action您想要执行的是print。这action是同样default actionawk

So even though

所以即使

awk 'NR>2{print}' filename

awk 'NR>2{print}' filename

would work fine, you can shorten it to

可以正常工作,您可以将其缩短为

awk 'NR>2' filename.

awk 'NR>2' filename.