Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk's ~ operator

Tags:

linux

bash

unix

awk

I'm having trouble with a basic search function that I'm working on bash.

Basically, I have a $file="Books.txt" and in it I have values separated by colon:

C++ Programming for Dummies:Bob:60:50:20
Catch Me If You Can: Mary Ann:40:30:20

The first 2 columns are titles and authors respectively. I'm trying to search by the titles of the books.

read -p "Title: " searchTitle

So far I have this code:

awk -v findTitle="$searchTitle" 'BEGIN {FS=":"; OFS=", ";} $1 ~ findTitle {print $1, $2, "$"$3, $4, $5}' $file

It works if I typed "Catch" in the prompt - Output:

Catch Me If You Can, Mary Ann, $40, 30, 20

However, If I searched for "C++", it gives me both -

Catch Me If You Can, Mary Ann, $40, 30, 20
C++ Programming for Dummies, Bob, $60, 50, 20

My question is: Why? I should be getting only the 'C++' book as a result. Is there other ways to get to the expected output? I tried to find answers but to no avail.

like image 635
Adam Winfield Avatar asked Sep 23 '26 12:09

Adam Winfield


1 Answers

You need to decide if you want to support regular expressions in your search or not. In any case you must use read -r flag to keep it from interpreting escape sequences and instead reading them as literal text.

If you want to search for fixed strings instead of patterns, use the index() function in awk:

read -r -p "Title: " searchTitle
awk -F: -v OFS=", " -v search="$searchTitle" '
    index($1,search) {
        print $1, $2, "$"$3, $4, $5
    }
' books.txt

If you want to support regular expressions, the code should look like this:

read -r -p "Title: " searchTitle
awk -F: -v OFS=", " -v search="$searchTitle" '
    $1 ~ search {
        print $1, $2, "$"$3, $4, $5
    }
' books.txt

However, you need to escape special regex characters in the case they appear in the pattern. The + from C++ is such a special character.

Since the strings get's parsed twice, once by the shell and once by awk, you need to double escape it:

Title: C\\+\\+
like image 165
hek2mgl Avatar answered Sep 26 '26 02:09

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!