Ubuntu – Asterisk not working with grep

command linegrepregextext processingwildcards

I searched for ki with * as per the example below and it should have returned the first three lines. I am not sure why it returns the last line when there is no ki matching it.

$ grep "ki*" trial_file.txt
kartik,27,Bangalore,Karnataka
pulkit,25,Bangalore,Karnataka
kit,28,Bangalore,Karnataka
kush,24,Pennsylvania,Philadelphia

Best Answer

Don't use * for this. Use grep 'ki' trial_file.txt or grep -F 'ki' trial_file.txt.

  1. Unless you pass it the -x/--line-regex option, grep will return lines that contain a match anywhere, even if the whole line isn't a match. So all you have to do is match part of the line. You don't have to do anything special to indicate there may be more characters.

  2. In a regular expression, * means "zero or more of the previous item." This is an entirely different from its meaning in shell pathname expansion (see also this article, man 7 glob, and this section). So, for example:

    • ax*b matches a, followed by any number of xes (even none), followed by b: ab, axb, axxb, axxxb, ...
    • a[xz]*b matches a followed by any number of characters where each is x or z, followed by b: ab, axb, azb, axxb, axzb, azxb, azzb, axxxb, ...
    • a(xyz)*b matches a, followed zero or more occurrences of the string xyz, followed by b: ab, axyzb, axyzxyzb, axyzxyzxyzb, ...

In this case, it seems like you're just searching for text. You don't need to use any regular expression metacharacters like ., *, or \ that have special meanings. That's why I suggest passing the -F flag, which makes grep search for "fixed strings" rather than performing regular expression matching.

If, however, you only want to match starting at the beginning of the line, then you do want to use a regular expression metacharacter: ^, as mjb2kmn suggests. This anchors your match to the start of the line. In that case you would run grep '^ki' trial_file.txt.

For more information on the options grep supports, see man grep and the GNU Grep manual.

Although in general I suggest enclosing regular expressions in ' ' quotes, in this case no quoting is necessary because the shell does not perform any expansions on ki or ^ki before passing them to grep.