Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep unknown number of spaces (linux)

Tags:

regex

grep

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.

like image 557
user2619315 Avatar asked Jul 25 '13 15:07

user2619315


2 Answers

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'."

like image 195
cdhowie Avatar answered Sep 18 '22 10:09

cdhowie


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

like image 29
David Hassan Avatar answered Sep 18 '22 10:09

David Hassan