user2619315
user2619315

Reputation: 111

Grep unknown number of spaces (linux)

Suppose you have a file named abc.txt - the file contains 2 (or generally more) lines:

word  -c           (09:35:20)
word     -c        (09:38:49)

If you run the command $ grep "word -c" abc.txt you get only the 1st line, because the number of spaces between 1 and -c does not match the 2nd line. Is there a way to fix this problem?

You cannot use grep'word1|word2' /path/to/file as the spaces between word and -c vary.

Upvotes: 9

Views: 20123

Answers (5)

chitresh
chitresh

Reputation: 346

you can use egrep with regex

egrep "word\s+-c" abc.txt

or

egrep "word +-c" abc.txt

Upvotes: 2

cdhowie
cdhowie

Reputation: 168988

Use the + regex character, which will match at least one of the preceding character:

grep -E "word +-c" abc.txt

This regex reads "match 'word', followed by one or more spaces, followed by '-c'."

Upvotes: 15

NOZUONOHIGH
NOZUONOHIGH

Reputation: 2006

cat /etc/ssh/sshd_config | egrep -v "^[[:space:]]?+#" | grep -v "^$"

this will remove any line that starts with # or any spaces before a #

Upvotes: 0

David Hassan
David Hassan

Reputation: 155

grep 'word *-c' abc.txt will work. I couldn't get grep 'word +-c' abc.txt to work.

Upvotes: 3

Curt
Curt

Reputation: 5722

grep 'word \+-c' abc.txt

Use single, not double, quotes. "+" signifies "one or more of the preceding expression, so would find any number of spaces (except zero).

Here's a reference: http://www.gnu.org/software/findutils/manual/html_node/find_html/grep-regular-expression-syntax.html

Upvotes: 0

Related Questions