bobylapointe
bobylapointe

Reputation: 683

GREP out lines with special characters except

I'm trying to add an exception to grep -v [[:punct:]] not to exclude lines with some predefined special characters. In the following example: - and _

Input:

Color red
Color _ yellow
Color blu+e
Color gr-een
Color bla!ck

Expected output:

Color red 
Color _ yellow
Color gr-een

Upvotes: 0

Views: 182

Answers (2)

glenn jackman
glenn jackman

Reputation: 246847

Instead of figuring out what you want to exclude, state what you want to keep:

grep '^[[:alnum:][:blank:]_-]*$'

Upvotes: 1

Jotne
Jotne

Reputation: 41456

Using awk you can do:

awk '/[-_]/ || !/[[:punct:]]/' file
Color red
Color _ yellow
Color gr-een

This gets lines that either of these:

  • have - or _.
  • do not contain [[:punct:]].

To solve problem with line like Color _ yellow !, you can do:

awk '/[-_]/ {a=$0;gsub(/[-_]/,"",a);if (a!~/[[:punct:]]/) print} !/[[:punct:]]/' file

Upvotes: 2

Related Questions