1

Suppose I have a couple of line formats:

this:foo ...
that: foo ...

And I want to run two different routines for one form or the other:

cat text_file \
| awk -F ':' '/:foo/ { # do this } # else print the whole line unchanged' 
| awk -F ':' '/ +foo +/ { # do that } # else print the whole line unchanged'

Ideally, I could write:

cat text_file \
| awk -F ':' '
   /:foo/ { ... }
   / +foo +/ { ... } 
   ...
   /.*/ { print }
'

But things seem to be behaving a lot differently than I expect. Is there a particular way to do this?

0
4

You can do:

awk '
    /:foo/ { print "do-things"; next }
    /[[:blank:]]+foo[[:blank:]]+/ { print "do-some-other-things"; next }
    { print "do-else" }
' infile

Note the next statement we used; that is to skip to running the rest of the codes if condition for given block was true; the last block will be execute if none of the two above blocks conditions were met.

4

I think you want:

awk -F: '
    $2 ~ /^[[:blank:]]/ {
        print "2nd field start with space"
    }
    $2 == "" || $2 ~ /^[^[:blank:]]/ {
        print "2nd field does not start with space"
    }
    { print }
' text_file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.