Delete Empty Lines Using Sed / Grep Command in Unix (or Linux)

  • Updated
  • Posted in Programming
  • 2 mins read


In Unix / Linux you should use the Sed / Grep command to take away empty traces from a file. For instance, Consider the beneath textual content file as enter

> cat file.txt
Remove line utilizing unix grep command

Delete traces utilizing unix sed command

How it really works

Now we are going to see take away the traces from the above file in unix / linux

1. Remove traces utilizing unix sed command

The d command in sed can be utilized to delete the empty traces in a file.

sed '/^$/d' file.txt

Here the ^ specifies the beginning of the road and $ specifies the tip of the road. You can redirect the output of above command and write it into a brand new file.

sed '/^$/d' file.txt > no_empty_lines.txt

2. Delete traces utilizing unix grep command

First we are going to see seek for empty traces utilizing grep command.

grep '^$' file.txt

Now we are going to use the -v choice to the grep command to reverse the sample matching

grep -v '^$' file.txt

The output of each sed and grep instructions after deleting the empty traces from the file is

Remove line utilizing unix grep command
Delete traces utilizing unix sed command
How it really works

Leave a Reply