Question

FILE:

hello

world

foo

bar

How can when remove all the empty new lines in this FILE?

Output of command:

FILE:

hello
world
foo
bar
Was it helpful?

Solution

grep . FILE


(And if you really want to do it in sed, then: sed -e /^$/d FILE)

(And if you really want to do it in awk, then: awk /./ FILE)

OTHER TIPS

Try the following:

grep -v -e '^$'
with awk, just check for number of fields. no need regex

$ more file
hello

world

foo

bar

$ awk 'NF' file
hello
world
foo
bar

Here is a solution that removes all lines that are either blank or contain only space characters:

grep -v '^[[:space:]]*$' foo.txt

Try this: sed -i '/^[ \t]*$/d' file-name

It will delete all blank lines having any no. of white spaces (spaces or tabs) i.e. (0 or more) in the file.

Note: there is a 'space' followed by '\t' inside the square bracket.

The modifier -i will force to write the updated contents back in the file. Without this flag you can see the empty lines got deleted on the screen but the actual file will not be affected.

grep '^..' my_file

example

THIS

IS

THE

FILE

EOF_MYFILE

it gives as output only lines with at least 2 characters.

THIS
IS
THE
FILE
EOF_MYFILE

See also the results with grep '^' my_file outputs

THIS

IS

THE

FILE

EOF_MYFILE

and also with grep '^.' my_file outputs

THIS
IS
THE
FILE
EOF_MYFILE

Try ex-way:

ex -s +'v/\S/d' -cwq test.txt

For multiple files (edit in-place):

ex -s +'bufdo!v/\S/d' -cxa *.txt

Without modifying the file (just print on the standard output):

cat test.txt | ex -s +'v/\S/d' +%p +q! /dev/stdin

Perl might be overkill, but it works just as well.

Removes all lines which are completely blank:

perl -ne 'print if /./' file

Removes all lines which are completely blank, or only contain whitespace:

perl -ne 'print if ! /^\s*$/' file

Variation which edits the original and makes a .bak file:

perl -i.bak -ne 'print if ! /^\s*$/' file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top