Can awk print lines that do not have a pattern?

大憨熊 提交于 2021-01-27 02:26:06

问题


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.


回答1:


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



回答2:


You can negate the pattern to get else like behavior:

awk '
    /pattern/ {
        # custom block to print the line    
    }
    !/pattern/ {
        # else do other things
    }
'



回答3:


You can do:

awk '/pattern/ {do something with line} 1' file

Here the 1 will print all lines, both the changed and the not changed line.


Just to show the solution Askan posted using else if

awk '{
    if (/pattern/)
        print "Line number:",NR,"pattern matched"
    else if (/Second/) 
        print "Line number:",NR,"Second matched"
    else 
        print "Line number:",NR,"Another line matched"
    }' file



回答4:


You can use switch if you are using gawk for example

awk '{switch ($0) {
case /pattern/:
    print "Line number:",NR,"pattern matched"
    break

case /Second/:
    print "Line number:",NR,"Second matched"
    break

default:
    print "Line number:",NR,"Another line matched"

}}' input.txt

input.txt

This line matches the pattern
Second line does not match
Hello
This line also matches the pattern
Another line

Output:

Line number: 1 pattern matched
Line number: 2 Second matched
Line number: 3 Another line matched
Line number: 4 pattern matched
Line number: 5 Another line matched

You can also group the cases by removing the break between them. more info




回答5:


echo -n "one\ntwo\nthree\nfour" | 
  awk '{a=1} /one/ {print 1;a=0} /three/ {print 3;a=0} a'

1
two
3
four


来源:https://stackoverflow.com/questions/23478755/can-awk-print-lines-that-do-not-have-a-pattern

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!