Home > Back-end >  grep matches exact string or with wildcard
grep matches exact string or with wildcard

Time:02-12

I want to search the content of a file that could contain for example:

name1
name2
name3
...
...
name10
name11
...
...

the search should match the string if it doesn't have a wildcard (*). for example :

grep -w name1 filename

it returns exactly what I want:

file1   #ignores file10 & file11 as no wildcard used

but when I use the same command but with wildcard (*), as follows:

grep -w name1* filename

it also returns file1 only. without file10 and file11. How can I match the string exactly as the first case and when a (*) is used it should include the others?

Note: I have seen some answers suggested using .* instead of * it worked but for my application the input is coming always in the form of * not .*

thank you in advance.

CodePudding user response:

grep uses for pattern matching. grep -w 'name1*' would make it match zero or more 1s, so name1 and name11 would match.

If it only matches name1 for you it's because you have a file named name1 in the directory and the unquoted name1* will be interpreted by the shell (globbing). Always use quotes around your arguments that contain special characters. If you use a variable, always put " around it.

To make it match any name starting with name1, make it

grep -w 'name1.*' filename
  • . means "any character"
  • .* means "any character, zero or more times".

If the input comes from some external source where * is used as a wildcard, you need to change that string before calling .

Example:

search_str='name1*'
new_search_str="$(sed 's/\*/.*/g' <<< "$search_str")"
grep -w "$new_search_str" filename
  • Related