Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk: print first line of file before reading lines

Tags:

bash

awk

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

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

ps aux | ggrep -Pi 'CPU|foo' 

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

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

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 BEGIN section of the awk command but that doesn't seem to work.

Any suggestions?

like image 824
Chris Schmitz Avatar asked Nov 28 '22 15:11

Chris Schmitz


1 Answers

Use the following awk script:

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:

ps aux | sed -n '1p;/PATTERN/p'
like image 86
hek2mgl Avatar answered Dec 04 '22 05:12

hek2mgl