0

Using AWK, want to print last line containing two specific words. Suppose I have log.txt which contains below logs

log1|Amy|Call to Bob for Food
log2|Jaz|Call to Mary for Toy and Cookies
log3|Ron|Call to Jerry then Bob for Book
log4|Amy|Message to John for Cycle

Now, Need to extract last line with "Call" and "Bob". I tried with-

#!/bin/bash
log="log.txt"
var="Bob"
check=$(awk -F'|' '$3 ~ "/Call.*$var/" {print NR}' $log | tail -1)
echo "Value:$check"

so Value:3 (3rd record) should be printed. But it's not printed.Please suggest. I have to use awk.

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82
  • possible duplicate of [How to use shell variables in awk script](http://stackoverflow.com/questions/19075671/how-to-use-shell-variables-in-awk-script) - you're nearly there, but the shell variable `$var` isn't being expanded inside the `awk` quotes - you need to pass it in as per the linked question – Josh Jolly May 16 '15 at 13:52
  • @AbhisekSen This is not a `design-patterns` question. Please read the description of a `tag` carefully before using it. – Chetan Kinger May 16 '15 at 14:39
  • @ChetanKinger man i tried pattern matching... mistakenly – Abhisek Sen May 16 '15 at 17:40
  • @JoshJolly: My question is not only how to use bash variable in awk, but also to search technique for the pattern having two specific words in it. – Abhisek Sen May 16 '15 at 17:51

1 Answers1

2

With GNU awk for word delimiters to avoid "Bob" incorrectly matching "Bobbing":

$ awk -v var="Bob" -F'|' '$3 ~ "Call.*\\<" var "\\>"{nr=NR; rec=$0} END{if (nr) print nr, rec}' file
3 log3|Ron|Call to Jerry then Bob for Book

See http://cfajohnson.com/shell/cus-faq-2.html#Q24. If Bob is already saved in a shell variable named var then use awk -v var="$var" ....

Ed Morton
  • 188,023
  • 17
  • 78
  • 185