1

I'm trying to use grep to find lines that has any other character except + and spacing.

I've tried using

grep [^+]

but if I test it with a text file:

++++++++
++++++++
+  ++ ++

which returns 3 empty lines.

The -c option returns 3 so I thought that spaces and newlines may be getting excluded so I tried

grep -c [^+\ ] and grep -c [^+\n\ ]

and both still gives me 3.

I've also tried

grep -v [+]

and though this code works with my above text file, I still need it to detect lines that also contain a mixture of +'s and other characters

For example, +1+++++ should also be included in the search, but was excluded.

What am I missing?

For clarification, on a text file like this:

++++++++
+  ++ ++
+1     +
abcd fgh
++++++++

I want it to return

+1     +
abcd fgh
1
  • Does your file have DOS-style \r\n line endings? Apr 8 at 12:49
2

Quote your pattern! This works just fine:

$ grep '[^+]' file
+  ++ ++

Your [^+] is interpreted as glob range pattern if unquoted (any file not matching +) and processed by your shell, grep will see file names macthing the glob.

In most shell implementations, one may also use ^ as the range negation character, e.g. [^[:space:]]. (via)

If you also want to exclude spaces, use [^+ ] as your pattern:

$ grep '[^+ ]' file2
+1     +
abcd fgh

You can check how your shell interprets your commands with set -x:

set -x
grep [^+] file
4
  • That still returns + ++ ++, though. I want grep to return all lines that contain characters other than +. I've edited my question for clarification.
    – klaus
    Apr 8 at 7:49
  • 2
    Then you need to also exclude spaces. Space is a character other than +.
    – pLumo
    Apr 8 at 7:51
  • I was just about to get back with that. It seems to be working now. Need to do some testing to make sure results are not due to chance.
    – klaus
    Apr 8 at 8:02
  • [^+ ] didn't work but including ^[:spaces:] worked. I think.
    – klaus
    Apr 8 at 8:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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