rzx0
rzx0

Reputation: 3

Replace previous when match regular expression

I need to delete the "end of line" of the previous line when current line starts is not a number ^[!0-9], basically if match, append to the line before, I'm a sed & awk n00b, and really like them btw. thanks

edit:

$ cat file

1;1;1;text,1
2;4;;8;some;1;1;1;more
100;tex
t
broke

4564;1;1;"also
";12,2121;546465

$ "script" file

1;1;1;text,1
2;4;;8;some;1;1;1;more
100;text broke 
4564;1;1;"also";12,2121;546465

Upvotes: 0

Views: 95

Answers (3)

kurumi
kurumi

Reputation: 25609

if you have Ruby on your system

  array = File.open("file").readlines
  array.each_with_index do |val,ind|  
    array[ind-1].chomp! if not val[/^\d/]    # just chomp off the previous item's \n
  end
  puts array.join

output

# ruby test.rb 
1;1;1;text,1
2;4;;8;some;1;1;1;more
100;textbroke
4564;1;1;"also";12,2121;546465

Upvotes: 0

potong
potong

Reputation: 58478

This might work for you (GNU sed):

sed -r ':a;$!N;s/\n([^0-9]|$)/\1/;ta;P;D' file

Keep two lines in the pattern space and if the start of the second line is empty or does not start with an integer, remove the newline.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204074

You didn't post any sample input or expected output so this is a guess but it sounds like what you're asking for:

$ cat file
a
b
3
4
c
d
$ awk '{printf "%s%s",(NR>1 && /^[[:digit:]]/ ? ORS : ""),$0} END{print ""}' file
ab
3
4cd

On the OPs newly posted input:

$ awk '{printf "%s%s",(NR>1 && /^[[:digit:]]/ ? ORS : ""),$0} END{print ""}' file
1;1;1;text,1
2;4;;8;some;1;1;1;more
100;textbroke
4564;1;1;"also";12,2121;546465

Upvotes: 2

Related Questions