user1739455
user1739455

Reputation: 25

using grep as if condition inside awk

I can use grep -Fxq search-string text-file outside of my awk, and it works they way I'd expect (found here How to test if string exists in file with Bash shell?). But, when I try to use that same grep command as an if statement inside awk, it seems to do nothing. Here's the basic usage I'm trying:

cat /var/log/somelogfile | awk '{ if (grep -Fxq $1 textfile) print "useful command $1" }'

Upvotes: 2

Views: 14532

Answers (4)

Ed Morton
Ed Morton

Reputation: 203324

It LOOKS like what you're trying to do is:

awk '
NR==FNR { strings[$0]; next }
{
    for (string in strings) {
        if ( index($0,string) ) {
            print "useful command", $1
            next
        }
    }
}
' textfile /var/log/somelogfile

We'll know for sure if/when you post some some sample input/output.

Upvotes: 1

Jakub M.
Jakub M.

Reputation: 33827

If grep or egrep are insufficient for your text filtering, it might be easier to a perl one liner. perl offers useful command line options, like -n -e which will implicitly executes your arbitrary command inside while loop.

So for example:

  perl -ne 'if (/some line (.*)/) {print "useful command: $1\n"}' /var/log/somelogfile

will filter all the lines with "some line" text and will print everything after that text.

Upvotes: 0

Tiago Lopo
Tiago Lopo

Reputation: 7959

There is no need for that, you can use anchors:

awk '/^search-string$/ {do something}'

Explanation:

  1. ^ Beginning of the line
  2. $ End of line
  3. /^search-string$/ return true if matches just like grep -Fxq

-x for grep uses anchors. I believe -F is redundant.

Upvotes: 1

djhaskin987
djhaskin987

Reputation: 10057

You can use awk's system function:

cat /var/log/somelogfile | awk '{ if (system("grep -Fxq " $1 " textfile")) print "useful command " $1; }'

See the docs.

Upvotes: 2

Related Questions