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?

ddzzbbwwmm
  • 2,265
  • 2
  • 19
  • 24

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
  • 976
  • 1
  • 6
  • 13
0
sed '/^$/d' file >newfile

...will do it for you.

tkosinski
  • 1,583
  • 12
  • 16
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
  • 13,751
  • 3
  • 35
  • 49