How to truncate empty lines using sed

Sed command is very helpful  for text processing. It’s just matter of regular expression. Here is how you can  truncate empty lines  in the file using command sed.

$ sed   '/^\s*$/d' <file_name>

The above command will give you the output by deleting empty lines. If you want to modify the original file itself. You use the option -i

$ sed  -i '/^\s*$/d' <file_name>

Example:

I have a file with following data and named as numbers

$ cat numbers
2989239823
8239823922

3892389239
2938923829
923892389

838888888



000000000

Now see, the way to truncate empty lines using sed

$ sed '/^\s*$/d' numbers 
2989239823
8239823922
3892389239
2938923829
923892389
838888888
0000000000

The above command won’t change the original file. If you want to change original use option -i

sed -i '/^\s*$/d' numbers 

Explanation:

Sed interprets ‘/^s*$/d’  and giving us the desired output. Here  text between slashes(/regular expression/) represent the regular expression followed by sed command “d”  means delete.  So command sed matches the lines with given regular expression. If it finds the match it applies the command.

 

One thought on “How to truncate empty lines using sed

Leave a Reply

Your email address will not be published. Required fields are marked *