LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   grep - remove lines which only contain whitespace. (https://www.linuxquestions.org/questions/linux-general-1/grep-remove-lines-which-only-contain-whitespace-721566/)

arizonagroovejet 04-25-2009 06:10 AM

grep - remove lines which only contain whitespace.
 
1 Attachment(s)
I'm having some trouble getting grep to remove lines from a file which only contain white space characters.

The attached file contains lines which are commented out by having a # at the start, lines which are empty and lines which contain either just some spaces or tab characters. I want to use grep to remove all the aforementioned types of line and end up with lines 2 3 6 13.

I thought that this would work:

grep -ve ^# lines.txt | grep -ve ^$ | grep -ve '^\s*$'

But it doesn't. The first and second greps do what I expect. The first one removes the commented out lines, the second removes the empty lines. The last grep, which I think should remove lines containing only whitespace characters doesn't remove anything and I can't figure out what the correct regexp should be. Anyone know?

druuna 04-25-2009 06:47 AM

Hi,

egrep -v "^[ ]*$|^#" lines.txt

There is a space and a tab between the square brackets. A tab can be 'cerated' by: ctrl-v then tab

Hope this helps.

arizonagroovejet 04-25-2009 07:02 AM

Quote:

Originally Posted by druuna (Post 3520403)
egrep -v "^[ ]*$|^#" lines.txt

Whilst I appreciate the suggestion, I really don't like that as a solution because of the invisibility of the tab character. It would be far too easy to forget that it's there, or to lose it in a copy/paste. I tried using

Code:

egrep -v "^[ \t]*$|^#" lines.txt
But that doesn't work.

druuna 04-25-2009 07:26 AM

Hi again,

I don't get the objection:

1) If you use this as a oneliner you type as you go and the oneliner is forgotten after you use it (getting it back from your history is a possibility).

2) If this is used in a script: A comment above the command should solve the forgetting part.

Anyway, here's another solution (but more typing... ;) ):

egrep -v "^[[:space:]]*$|^#" lines.txt

arizonagroovejet 04-25-2009 09:41 AM

That's great, thanks a lot.


All times are GMT -5. The time now is 08:27 AM.