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.
CodePudding user response:
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