Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing lines in a text file based on the beginning characters

Tags:

ruby

I have an email message which looks like this:

Hey how are you?

On Saturday [email protected] wrote:
> something
> On Friday [email protected] wrote:
>> previous thing

How would I remove the lines that start with > as well as lines that include [email protected] wrote

Should I even keep the "someone wrote" part as that could remove legitimate lines, maybe only removing that line if it's the last line.

I'm trying this out:

message_filtered = message_txt.to_s.split("\n").each do |m|
  if m[0] != ">" then
    return m
  end
end

puts message_filtered

I could push m to an array and then join that array with \n but i'm trying a shorter way.

like image 394
Joseph Le Brech Avatar asked Feb 17 '12 16:02

Joseph Le Brech


2 Answers

Try

message_filtered = message_txt.lines.reject { |line|
  line[0] == '>' || line =~ YOUR_EMAIL_REGEXP
}.join('\n')

To remove lines that start with > you can use:

message_filtered = message_txt.gsub(/(^>.+)/, '') # should work but not tested
like image 160
Hauleth Avatar answered Sep 20 '22 15:09

Hauleth


my proposition:

message_filtered = '';
message_txt.to_s.lines {|line| message_filtered << line unless line[0] == '>' }
like image 22
Baldrick Avatar answered Sep 21 '22 15:09

Baldrick