TurtleOrRodeo
TurtleOrRodeo

Reputation: 63

Excluding lines that start with space from egrep printout

I'm trying to write a regex (e)grep command that will print all the lines in txt file, but ignore those that begin with a space (manually indented file). I haven't been able to figure out how to use the start of line ^ and exclude ^ together. Thanks!

Upvotes: 2

Views: 4683

Answers (2)

Will
Will

Reputation: 24699

A good way to do this is with a negated character class.

Much like [abc] will match a, b, or c, [^abc] will match any character that is NOT a, b, or c. The ^ anchors the regex at the beginning of the line, so what follows it has to match the first character of the string.

$ cat test
does not start with space
 starts with space
       starts with more spaces
another good line

$ egrep '^[^ ]' test
does not start with space
another good line

If we want to skip lines starting with whitespace, including tabs, you can use the special [:space:] bracket expression inside the character class:

 egrep '^[^[:space:]]' test

If you aren't looking for other things in the lines, you can also use an inverted match:

 -v, --invert-match
         Selected lines are those not matching any of the specified pat-
         terns.

So we could do this instead:

 egrep -v '^[[:space:]]' test

grep should do this too:

 grep -v '^[[:space:]]' test

Upvotes: 4

Chad
Chad

Reputation: 693

You can use the -v switch to skip matching lines.

egrep -v '^ '

See man egrep

Upvotes: 1

Related Questions