LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   removing blank lines in a text file (https://www.linuxquestions.org/questions/linux-newbie-8/removing-blank-lines-in-a-text-file-594604/)

christianunix 10-25-2007 03:32 PM

removing blank lines in a text file
 
how do I delete all blank lines in a text file? thanks :)

bjagee 10-25-2007 03:36 PM

There are a thousand ways to do that. If you want to do it from the ci:
Code:

    cat file-blanklines-2-be-deleted | sed -e '/^$/d' | tee newfile-no-blanklines
Or, if you prefer vi/vim:
Code:

    :g/^[ t]*$/d  --> WHERE t=tab

weibullguy 10-25-2007 03:37 PM

Look at table C-2 --> http://tldp.org/LDP/abs/html/abs-guide.html#AEN20423

The_JinJ 10-25-2007 03:38 PM

Used this in the past to strip blank lines and comments

Code:

sed '/ *#/d; /^ *$/d' test.txt2

0.o 10-25-2007 03:39 PM

Why couldn't you just use: sed /^$/d < oldfile > newfile

complich8 10-25-2007 03:46 PM

I prefer grep:
#print only lines that contain non-whitespace characters
grep '[^[:space:]]' oldfile > newfile

ghostdog74 10-25-2007 06:39 PM

Quote:

Originally Posted by bjagee (Post 2936839)
There are a thousand ways to do that. If you want to do it from the ci:
Code:

    cat file-blanklines-2-be-deleted | sed -e '/^$/d' | tee newfile-no-blanklines

you can skin the cat
Code:

sed -e '/^$/d' file-blanklines-2-be-deleted
and if your sed supports -i option
Code:

sed -ie '/^$/d' file-blanklines-2-be-deleted

custangro 10-25-2007 06:42 PM

or vi the file and in command mode do this:

Code:

%s/ //g

bjagee 10-26-2007 12:46 PM

Quote:

Originally Posted by custangro (Post 2937032)
or vi the file and in command mode do this:

Code:

%s/ //g

That will only eliminate spaces, and it will do so in sentences too. You would still have blank lines and tabsbutyourwordswouldallruntogether.

matthewg42 10-26-2007 01:28 PM

If you want to modify the original file (instead of creating a second, modified one), you can use the -i option. This version also deletes lines with spaces and tabs on... maybe you want to keep them, I don't know:
Code:

sed -i '/^[ \t]*$/d' the_file_to_modify

custangro 10-26-2007 02:52 PM

Quote:

Originally Posted by bjagee (Post 2937889)
That will only eliminate spaces, and it will do so in sentences too. You would still have blank lines and tabsbutyourwordswouldallruntogether.

Sorry, I miss understood the question, the correct syntax is this (in vi command mode):

Code:

g/^$/d
-custangro

bjagee 10-29-2007 12:24 AM

That's the ticket. You could also use \s in that to get lines that have non-printing chars:
Code:

: %s:\s:g


All times are GMT -5. The time now is 12:18 AM.