Flethuseo
Flethuseo

Reputation: 6199

search and replace with scan

I want to search and replace some digits in a text file and that are separated by spaces and merge them together

like

asdf asdf 1 2
3 asdf asdf asdf
2 3 asdf

to

asdf asdf 123
asdf asdf asdf
23 asdf

I tried the following, but it doesn't work, and I am not sure how to best do the replacing in the file:

text = File.read("testfile.txt")
p text.scan(/([\d+\s+\d+]+)/)

Upvotes: 0

Views: 666

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146123

FN = 'thefile'
result = File.read(FN).gsub /(\d)\s+(?=\d)/, '\1'
open(FN, 'w') { |io| io.write(result) }

Upvotes: 1

sawa
sawa

Reputation: 168199

Actually, you don't need \d+. \d will suffice.

gsub(/(\d)\s+(?=\d)/, '\1')

If you have oniguruma installed or are using ruby1.9,

gsub(/(?<=\d)\s+(?=\d)/, '')

Upvotes: 1

Related Questions