bash awk:在读取行之前打印文件的第一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22284968/
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-18 09:51:30  来源:igfitidea点击:

awk: print first line of file before reading lines

bashawk

提问by Chris Schmitz

How would I go about printing the first line of given input before I start stepping through each of the lines with awk?

在开始使用 awk 单步执行每一行之前,我将如何打印给定输入的第一行?

Say I wanted to run the command ps auxand return the column headings and a particular pattern I'm searching for. In the past I've done this:

假设我想运行命令ps aux并返回列标题和我正在搜索的特定模式。在过去,我已经这样做了:

ps aux | ggrep -Pi 'CPU|foo' 

Where CPUis a value I know will be in the first line of input as it's one of the column headings and foois the particular pattern I'm actually searching for.

CPU我知道输入的第一行中的值在哪里,因为它是列标题之一,并且foo是我实际搜索的特定模式。

I found an awk pattern that will pull the first line:

我找到了一个 awk 模式,它将拉出第一行:

awk 'NR > 1 { exit }; 1'

Which makes sense, but I can't seem to figure out how to fire this before I do my pattern matching on the rest of the input. I thought I could put it in the BEGINsection of the awk command but that doesn't seem to work.

这是有道理的,但在我对其余输入进行模式匹配之前,我似乎无法弄清楚如何触发它。我以为我可以把它放在BEGINawk 命令的部分,但这似乎不起作用。

Any suggestions?

有什么建议?

回答by hek2mgl

Use the following awk script:

使用以下 awk 脚本:

ps aux | awk 'NR == 1 || /PATTERN/'

it prints the current line either if it is the first line in output or if it contains the pattern.

如果当前行是输出中的第一行,或者它包含模式,则它会打印当前行。

Btw, the same result could be achieved using sed:

顺便说一句,使用sed以下方法可以获得相同的结果:

ps aux | sed -n '1p;/PATTERN/p'

回答by Henk Langeveld

Explaining awk BEGIN

awk 解释 BEGIN

I thought I could put it in the BEGIN section ...

我以为我可以把它放在 BEGIN 部​​分......

In awk, you can have more than one BEGINclause. These are executed in orderbeforeawk starts to read from stdin.

在 中awk,您可以有多个BEGIN子句。这些awk 开始读取之前按顺序执行。stdin

回答by Dave

If you want to read in the first line in the BEGINaction, you can read it in with getline, process it, and discard that line before moving on to the rest of your awk command. This is "stepping in", but may be helpful if you're parsing a header or something first.

如果你想读入BEGIN动作的第一行,你可以用 读入getline,处理它,然后在继续执行 awk 命令的其余部分之前丢弃该行。这是“介入”,但如果您首先解析标题或其他内容可能会有所帮助。

#input.txt
Name    City
Megan   Detroit
Hymanson Phoenix
Pablo   Charlotte

awk 'BEGIN { getline; col1=; col2=; } { print col1, ; print col2,  }' input.txt

# output
Name Megan
City Detroit
Name Hymanson
City Phoenix
Name Pablo
City Charlotte