Delete unknown number of lines from * until blank line

sed

I've been using this forum, so I just now joined! I have seen similar questions but nothing has worked so far (mostly using sed). I want to find each instance of an asterisk (*) in a file and delete it and everything after it until a blank line is reached. For example:

*252
253
254
255
(blank line here)

OR

*261
265
(blank line here)

Each block of data will vary in length. Then I want to have output go to a new file. Any ideas?

Best Answer

To delete from a line containing * to the next empty line, use:

sed '/[*]/,/^$/d' filename

Notes:

  1. Since * is a regex-active character and we only want to match a literal *, we need to escape the *. This could be done as \* or, as shown above, [*].

  2. To match an empty line, we need a line with no characters between its beginning, denoted ^, and its end, denoted $. Thus ^$ matches an empty line.

  3. /[*]/,/^$/ is a range: it matches a group of lines that start with a line containing * and end with an empty line.

  4. d tells sed to delete any line in the range.

The above produces output to stdout. To change a file in place, use:

sed -i.bak '/[*]/,/^$/d' filename

Example

Consider this sample file:

$ cat filename
*252
253
254
255

OR
*261
265

end

This produces:

$ sed '/[*]/,/^$/d' filename
OR
end
Related Question