Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can awk print lines that do not have a pattern?

Tags:

awk

Can awk print all lines that did not match one of the patterns?

In other words, I want to transform some lines but leave the rest unchanged. So, if a /pattern/ matched I would provide a custom block to print the line. I just need to provide a default matcher (like an else) to print the other lines.

like image 370
jcalfee314 Avatar asked May 05 '14 17:05

jcalfee314


People also ask

What is awk pattern?

Awk is a programming language whose basic operation is to search a set of files for. patterns, and to perform specified actions upon lines or fields of lines which contain. instances of those patterns. Awk makes certain data selection and transformation opera- tions easy to express; for example, the awk program.

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.


2 Answers

You can negate the pattern to get else like behavior:

awk '
    /pattern/ {
        # custom block to print the line    
    }
    !/pattern/ {
        # else do other things
    }
'
like image 154
Cole Tierney Avatar answered Sep 28 '22 04:09

Cole Tierney


Yes, just use any non-zero number and awk will do its default thing which is to print the line:

awk '7' file

If you want it as an "else", put "next" after whatever lines you select for special processing so this one isn't executed for them too.

awk '/pattern/{special processing; next} 7' file
like image 20
Mark Setchell Avatar answered Sep 28 '22 04:09

Mark Setchell