简体   繁体   中英

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:

bookname:authorname:price

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM