0

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.

3
  • this sounds like an XY Problem .. why do you have to use * and not .*? (ie. though I wouldn't suggest it, could you just prepend . to *?) where does the input come from? do you have to use grep?
    – ti7
    Feb 11, 2022 at 22:57
  • @ti7 I don't have to use grep, It is just the first thing that came to my mind. the input coming from an external source with * not .*
    – Mhd Ghd
    Feb 11, 2022 at 23:02
  • Which other characters do you need treated as non-literal? For example if the input contained foo and the argument given to search for was fo. should that match or not?
    – Ed Morton
    Feb 16, 2022 at 0:08

1 Answer 1

0

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
2
  • The issue is the input recieved using * instead of the .* Is there an alternative or a way to go beyond that?
    – Mhd Ghd
    Feb 11, 2022 at 22:50
  • @MhdGhd I just added a way to deal with that.
    – Ted Lyngmo
    Feb 11, 2022 at 22:51

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.