2

Inside this directory

mael@mael-HP:~/repertoireVide$ 

Is a file called MySQLServe containing the words violon and avion:

mael@mael-HP:~/repertoireVide$ cat MySQLServ
violon avion

Why would these grep command applied in the current directory

$ grep -r  ^[^a]*$

$ grep -r  '^[^a]*$'

Not give any output?

The ^ followed by [^a] should omit avion from the search, but the *$ part of the argument should accept any other word with any possible ending. Why is violon excluded here?

Thanks.

1 Answer 1

3

You do not get any result because your regular expression, ^[^a]*$ (which should be quoted using single quotes as in your second attempt), matches lines that contains only non-a characters (or empty lines), and your text string is not empty and it does contain an a.

The * acts on the previous expression, [^a] in this case. [^a]* will match zero or more non-a characters. Since you anchor the expression to both start and end of the line around this, it rejects any line that contains the letter a.

To grep for lines that start with something that is not a, use

grep -r '^[^a]' .

Note that it is not necessary to explicitly match tho whole line, but if you want to do that, use

grep -r '^[^a].*$' .

.* matches zero or more of any character (including a).

To also get empty lines in the output (these obviously don't start with a):

grep -r -v '^a' .

That is, match an a at the start of a line and invert the sense of the match using -v. This way you don't require any characters at all in a line (note that to match [^a], there has to be at least one character), but if there are some, the first one shouldn't be an a.

To search for words that don't start with a, use

grep -r -w -o '[^a][[:alpha:]]*' .

That expression matches anything that starts with something other than a, and then continues with zero or more alphabetic characters. The -w option to GNU grep restricts the matches to words, and the -o option asks grep to only extract the matching parts from each line.

1
  • Note that if you had the words in separate lines you would get the desired result (violon but not avion). Commented Oct 26, 2019 at 9:21

You must log in to answer this question.

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