ricknaght
ricknaght

Reputation: 93

Keeping non-blank comment lines with SED

I'm trying to keep only the comment lines starting with # that aren't blank with a sed command on a single line. I'm trying this

sed /^#\S+/'!'d file

However, this prints nothing.

Say the file looks something like this

 # comment
 # another comment
 #   
 #    
 #
 line1
 line2
 # extra comment

And I want

 # comment
 # another comment
 # extra comment`

My command provides no output at all. I'm trying to do this on the simplest way possible. Any idea?

Upvotes: 1

Views: 625

Answers (3)

Ed Morton
Ed Morton

Reputation: 203209

$ grep '#.*[^[:blank:]]' file
 # comment
 # another comment
 # extra comment

$ sed -n '/#.*[^[:blank:]]/p' file
 # comment
 # another comment
 # extra comment

$ awk '/#.*[^[:blank:]]/' file
 # comment
 # another comment
 # extra comment

Upvotes: 2

hidefromkgb
hidefromkgb

Reputation: 5903

Is SED a must? If not, you can try, for example, grep '^\s*#.*[^\s]' — it prints any line containing a comment sign after 0 or more whitespace characters, which also contains at least one non-whitespace character.

Upvotes: 1

heemayl
heemayl

Reputation: 41987

With sed:

sed -n '/^[[:blank:]]*#[[:blank:]]*[^[:blank:]]/p'
  • The character class [:blank:] includes space and tab

  • ^[[:blank:]]* matches zero or more blanks at start

  • # matches a literal #, then [[:blank:]]* matches zero or more blanks

  • [^[:blank:]] matches any character except space or tab

Note that, not all seds support expansion of special sequence \S to any non-whitespace.

Example:

$ cat file.txt
# comment
 # another comment
 #

 #

 #
 line1
 line2
 # extra comment

$ sed -n '/^[[:blank:]]*#[[:blank:]]*[^[:blank:]]/p' file.txt
# comment
 # another comment
 # extra comment

Upvotes: 3

Related Questions