Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Awk how to find a match of variable with paranthesis?

I have a file some_file.txt , in which I want to find a match line by name inside square brackets (it must bee exact match as some words may be repeated – like foo in example below).
The document contents looks like this:

[foo](url)
[foo Foo](url)
[bar (Bar)](url)
[fizz buzz](url)

I came up with the following, but it breaks when you specify name with paranthesis.

file="some_file.txt"

name="foo" # Good
name="foo Foo" # Good
name="bar (Bar)" # No match :(
name="fizz buzz" # Good

matched_line=$(awk -v n="${name}]" '$0 ~ n {print NR}' "${file}")

I tried to escape paranthesis like so name="bar \(Bar\)", but it doesn’t help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a non-regex search using index function:

awk -v n='bar (Bar)' 'index($0, n) {print NR}' file
3

# be more precise and search with surrounding [ .. ]
awk -v n='bar (Bar)' 'index($0, "[" n "]") {print NR}' file
3

index function preforms plain text search in awk hence it doesn’t require any escaping of special characters.

Using all search terms:

for name in 'foo' 'foo Foo' 'bar (Bar)' 'fizz buzz'; do
   awk -v n="$name" 'index($0, "[" n "]") {print NR, n}' file
done

1 foo
2 foo Foo
3 bar (Bar)
4 fizz buzz
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading