Sharad Shrestha
Sharad Shrestha

Reputation: 169

How to remove line that starts with + or - followed by empty space only

Here is a file that contains:

+ 
- 
+ <>cow apple</>
- apple
+ ball
+ +
- -
+ -
- +
+ !
- 
- 
+ 
+ $
+ **
+ *
+ =
+ #
- ?
- ◊
+ ◊◊
- 
- 

Expect output:

+ <>cow apple</>
- apple
+ ball
+ +
- -
+ -
- +
+ !
+ $
+ **
+ *
+ =
+ #
- ?
- ◊
+ ◊◊

How to remove line that starts with + or - followed by empty space only?

Here is code which gives expected result but better solution would be very helpful. Since I am running this cmd on large file and has to be accurate.

sed ‘/^[^[:alnum:]]* $/d’

Upvotes: 1

Views: 41

Answers (2)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

grep '^[+-]\s\S' file
  • ^ start of line anchor
  • [+-] match on + or -
  • \s match a whitespace
  • \S match a non-whitespace

Upvotes: 1

anubhava
anubhava

Reputation: 785058

You may use this grep with -v (inverse) option:

grep -v '^[-+][[:blank:]]*$' file
+ <>cow apple</>
- apple
+ ball
+ +
- -
+ -
- +
+ !
+ $
+ **
+ *
+ =
+ #
- ?
- ◊
+ ◊◊

Here:

  • ^[-+][[:blank:]]*$: Matches a line starting with - or + followed by 0 or more whitespaces till end.

Following awk or sed solutions would also work:

sed '/^[-+][[:blank:]]*$/d' file

awk '!/^[-+][[:blank:]]*$/' file

Upvotes: 3

Related Questions