0

I used sed '/pattern/d' file > newfile to remove some lines in a text file, but there are lots of blank lines left in the new file.

How can I modify the command to avoid the blank lines?

wsdzbm
  • 3,096
  • 3
  • 25
  • 28
  • Check your file for special characters: `cat -A file` or `cat -v file` – Cyrus Jun 20 '16 at 17:19
  • @Cyrus `-A` shows lots of blank lines in original file. `-v` just prints the text. – wsdzbm Jun 20 '16 at 17:28
  • 2
    Possible duplicate of [Delete empty lines using SED](http://stackoverflow.com/questions/16414410/delete-empty-lines-using-sed) – hek2mgl Jun 20 '16 at 17:34

3 Answers3

1
sed '/pattern/d; /^$/d' file > newfile

There is some good discussion about regular expressions for deleting empty lines in a file in this Stack Overflow post

Community
  • 1
  • 1
Amit
  • 1,006
  • 1
  • 7
  • 13
0
sed '/^$/d' file >newfile

...will do it for you.

tkosinski
  • 1,631
  • 13
  • 17
0

The command that you use will delete all the lines you want to delete, but it leaves the blank lines that are already there in the original file in place. To delete these too, simply apply a second filter to the input:

$ sed -e '/pattern/d' -e '/^[:blank:]*$/d' <file >newfile

The second filter will remove lines that are empty, or that contains only whitespace characters (i.e., that are "blank" in their appearance).

Kusalananda
  • 14,885
  • 3
  • 41
  • 52