Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How do I delete lines beginning with a #, given that there can be whitespace on the left and right of the #?

  # Master socket provides access to userdb information. It's typically
share|improve this question
add comment

6 Answers 6

This seems to work, but I've not given deep thought to it:

sed -e '/^[[:space:]]*#/d'
share|improve this answer
    
Sorry, no. There are still comment-lines in the output. I tested on dovecot.conf. –  chris4000 Nov 28 '11 at 13:38
2  
Try now. Ulrich had forgotten the extra [ and ]. –  rozcietrzewiacz Nov 28 '11 at 13:42
    
Thank you. that worked. –  chris4000 Nov 28 '11 at 13:46
add comment

You can use grep for that

grep -vh '^[[:space:]]*#' filename

Since, as I presume, you are stripping comments from some file, you might also consider removing empty lines, which expands the above to:

grep -vh '^[[:space:]]*\(#\|$\)' filename
share|improve this answer
    
the second version is most comfortable. thank you. –  chris4000 Nov 28 '11 at 13:46
add comment

awk solution is to invert matching your pattern.

$> cat ./text
elephant
# Master socket provides access to userdb information. It's typically
zoo
 #ok
penguin
# !

$> awk '!/^(\ )*#/ {print $0}' ./text
elephant
zoo
penguin
share|improve this answer
4  
No need to escape the space character, no need to capture the space character, no need to specify the default action: awk '!/^ *#/' ./text. –  manatwork Nov 28 '11 at 15:42
    
awk '/^ *#/{next}1' file should be good enough. –  jaypal Dec 23 '11 at 5:01
add comment
perl -ne 'print if ! /^\s*#/' ./text
share|improve this answer
    
hi @Peter-john-acklam, would this work when the code is followed by # comment? –  Nikhil Mulley Jan 14 '12 at 10:47
add comment

Using the sample data posted by ДМИТРИЙ МАЛИКОВ...

$ grep -vPh '^\s*#' filename.txt | grep -Po '\w+'
elephant
zoo
penguin

I prefer using pcre with grep so I use the -P switch for grep (must be GNU grep). The second grep is pure sugar to give you the words with no white-space. It would also "remove" empty lines.

share|improve this answer
add comment
$ perl -pi -e '$_="" if /^\s*#/' filename
share|improve this answer
    
That's not good - doesn't delete lines, and clears lines like a#b –  Mat Dec 12 '11 at 4:23
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.