JamesPoppycock JamesPoppycock - 1 year ago 105
Bash Question

awk does not print line number

I have the following code

awk -v bookName="$bookName" -v authorName="$authorName" '/bookName:authorName/{print NR}' BookDB.txt

My bookDB.txt contains text with syntax as shown:


The code above aims to match exactly "bookname:authorname" and print out the line number where it match. However, it is not printing out anything.

I don't find anything wrong in the code syntax.
Any help will be greatly appreciated.

Answer Source

The issue is that you're trying to use awk variables within / /, which you can't do.

Change your condition to $0 ~ bookName ":" authorName to search the whole record $0 for the pattern.

Alternatively, if the fields in your file are separated by :, you could also set the input field separator using -F: and then use string comparisons on the first two fields:

awk -F: -v book="$bookName" -v author="$authorName" '
    $1 == book && $2 == author{print NR}' BookDB.txt