user3787067
user3787067

Reputation: 21

Delete two lines with sed if no text between them

i have a file that contain the following text:

[Data]

hi

[Data]

one two three

[Data]

[Data]

right left

[Data]

[Data]

I am looking how to get this output from sed, awk or something:

[Data]

hi

[Data]

one two three

[Data]

right left

Explanation: i need to look if between [Data] and [Data] have no text, if not contain text i need to delete the [Data] line and the next empty line.

Can you help me? many thanks!

Upvotes: 0

Views: 78

Answers (5)

potong
potong

Reputation: 58361

This might work for you (GNU sed):

sed ':a;$!{N;s/\n/&/3;Ta};/^\[Data\][^\n]*\n\n[^[][^\n]*\n$/b;s/\n//;D' file

This keeps a rolling window of 4 lines in the pattern space and if the expected pattern is not found, deletes the first two lines then regenerates the pattern space back up to 4 lines and repeats.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203169

This does what you SAY you want to do using GNU awk for multi-char RS and \s shorthand for [[:space:]]:

$ awk -v RS='^$' -v ORS= '{gsub(/\[Data\]\s*\[Data\]/,"[Data]")}1' file
[Data]

hi

[Data]

one two three

[Data]

right left

[Data]

I emphasize "SAY" because your posted expected output doesn't match your description of what you want to do (i need to look if between [Data] and [Data] have no text, if not contain text i need to delete the [Data] line and the next empty line.) in as much as it also seems to delete a "[Data]" line at the end of the file.

Upvotes: 0

Scrutinizer
Scrutinizer

Reputation: 9926

The title says sed but it is also tagged awk, so try:

awk '$0==s && p==$0{next} {p=$0}1' s="[Data]" file

This is presuming there are no empty lines every other line in the real data sample.

Upvotes: 2

dvk317960
dvk317960

Reputation: 792

Hope this will be helpful.

sed ':a;/$/{N;s/\n/#/;ba}' inputFile.txt|sed 's/\]#*\[Data\]/\]/g'|sed 's/#/\n/g

Upvotes: 0

Farvardin
Farvardin

Reputation: 5414

try this:

sed ':a;N;$!ba;s/\n/###/g' file | sed 's/######\[Data\]######\[Data\]/######\[Data\]/g' | sed 's/###/\n/g'

Upvotes: 0

Related Questions