beyonddc
beyonddc

Reputation: 1256

Ruby one liner to match multiple lines

I have a text file that has the following content.

one two three
four five six
seven eight nine
ten eleven twelve

I am trying to convert the following Ruby code to a Ruby one liner command where it replace two lines (four five six and seven eight nine) with empty space.

input = File.new('./test', 'r+')
content = input.read
input.close

modified = content.sub("four five six\nseven eight nine", "")
print modified

I tried something like this but no luck.

ruby -pe 'gsub(/four five six\nseven eight nine/,"")' < ./test

Any idea? Thanks!

Upvotes: 0

Views: 676

Answers (3)

The -p flag causes Ruby to "assume 'while gets(); ... end' loop around your script" (from ruby -h), thus running the command on each line separately, and then print the output. Instead, do an explicit gets(nil) to cause it to take in the whole input at once, then call puts on that (and add another \n at the end of the regex so it doesn't leave a blank line):

ruby -e 'puts gets(nil).gsub(/four five six\nseven eight nine\n/,"")' < ./test
one two three
ten eleven twelve

Upvotes: 4

struthersneil
struthersneil

Reputation: 2750

Quick sanity check; Ruby matches newlines without a problem:

2.0.0-p195 :159 > /abc\ndef/ === "abc\ndef"
 => true 

There are some caveats (use the m modifier if you want . to match \n!)

2.0.0-p195 :161 > /.{7}/ === "abc\ndef"
 => false 
2.0.0-p195 :162 > /.{7}/m === "abc\ndef"
 => true 

Perhaps you have some whitespace or something at the ends of your lines, so take that into account in your regex (/four five six\s*\nseven eight nine/m)

Upvotes: 2

abiessu
abiessu

Reputation: 1927

Try a regex "or": /(four five six|seven eight nine)/. In a case like this on the command line, it is often the case that the file will be read line-by-line.

Upvotes: 1

Related Questions