2

I'm new to Linux and so far I've been playing around with some utilities, specifically the grep utility. I decided to create a new file (aptly called 'newfile') with the following content:

Lady of the night,
I hold you close to me,
And everything is out of sight,
I think I'll be alright.

When I try to run it through grep by entering 'grep .* newfile' I was expecting only the lines of the file to show up; however, it printed several results, starting with:

grep: ..: Is a directory

And following up with the entirety of .bash_history (which I'll leave out for the sake of keeping this post short), and then the contents of newfile. Why is this so? Is there a way I can fix this? Do I have to alter my regular expression?

3 Answers 3

5

Do an experiment! Run

echo grep .* newfile

What can you conclude from the result? How does the result change when you quote (place in single or double quotes) the first argument to grep?

If you want the straight dope on this, read the POSIX spec for Pathname Expansion. Knowing everything about the various expansions will turn you into a shell guru in no time :-)

1
  • 1
    @drewbenn Good point. But I think you meant pathname expansion (aka globbing).
    – Jens
    Jun 17, 2015 at 18:18
0

The shell is interpreting your *, not passing it to grep as a regex. To use a regex search with grep, you'll have to pass it an option telling it "this is a regex" - on my installation, it's -e. Try grep -e '.*' newfile.

1
  • 1
    -1: You don't have to pass -e to grep to tell it "this is a regex"; grep expects a regex by default. The -e option is only useful for preventing a pattern starting with - from being recognized as an option, which -- could be used for as well (assuming GNU grep). In this case, grep -e ".*" file and grep ".*" file behave identically.
    – godlygeek
    Jun 17, 2015 at 18:25
-2

By specifying the dot before the asterisk (.*) and the file name (newfile), you are telling grep to look for the pattern .\* in the file newfile, and the shell is expanding .\* to include the dot files in your directory.

You probably want something like:

cat newfile

which will print the lines of your file.

1
  • 3
    Sorry, no. The .* is expanding to the list of dot files in the current directory. grep uses the first item (i.e. the first filename) as its regular expression and the remainder of the line as the set of files to search. See what I mean with echo grep .* newfile Jun 17, 2015 at 18:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .