I tried to find a simple solution to replace a particular character randomly within a file.
Unfortunately, my solution replaces all found characters and not just some of them.
file_names = ['users_controller.rb']
file_names.each do |file_name|
text = File.read(file_name)
new_contents = text.gsub(",", ";") #replaces , to ; (unfortunatly all and not just some)
puts new_contents
File.open(file_name, "w") {|file| file.puts new_contents }
end
I appreciate any help, thanks.
The question is not clear. If you want to replace some random occurrences of a particular (fixed) character (",") with a particular (fixed) character (";"), then do:
text.gsub(","){rand(2).zero? ? "," : ";"}
Related
I have a file formatted by lines like this (I know it's a terrible format, I didn't write it):
id: 12345 synset: word1,word2
I want to read the entire file and check to see if every line is correct without having to look line by line.
I've looked into File and Regex, but couldn't find what I need. I tried to use File.read to read the entire file all at once, then use m modifier for regex to check multiple lines, but it's not working the way I anticipated (perhaps it's not what I need).
p.s. Ruby newbie :)
Assuming your file always ends with a newline, this should work:
/^(id: \d+ synset: \w+,\w+\n)+$/m
The full ruby:
content = ''
File.open('myfile.txt', 'r') { |f| content = f.read }
puts 'file is valid!' if content =~ /^(id: \d+ synset: \w+,\w+\n)+$/m
You can use this regex to check each line of the file: ^id:\s*\d+\s+synset:\s*(?:\w+,)*\w+$. You can try the following code, but I don't know any Ruby, I just searched and tested a little. It might work.
line_num = 0
text = File.open('file.txt').read
text.each_line do |line|
line_num += 1
if !/^id:\s*\d+\s+synset:\s*(?:\w+,)*\w+$/.match(line)
print "Line #{line_num} is incorrect"
end
end
New to ruby here!
How to replace the whole line in a text file which contains a specific string using ruby?
Example: I want to remove and add the whole line contains "DB_URL" and add something like "DB_CON=jdbc:mysql:replication://master,slave1,slave2,slave3/test"
DB_URL=jdbc:oracle:thin:#localhost:TEST
DB_USERNAME=USER
DB_PASSWORD=PASSWORD
Here is your solution.
file_data = ""
word = 'Word you want to match in line'
replacement = 'line you want to set in replacement'
IO.foreach('pat/to/file.txt') do |line|
file_data += line.gsub(/^.*#{Regexp.quote(word)}.*$/, replacement)
end
puts file_data
File.open('pat/to/samefile.txt', 'w') do |line|
line.write file_data
end
Here is my attempt :
file.txt
First line
Second line
foo
bar
baz foo
Last line
test.rb
f = File.open("file.txt", "r")
a = f.map do |l|
(l.include? 'foo') ? "replacing string\n" : l # Please note the double quotes
end
p a.join('')
Output
$ ruby test.rb
"First line\nSecond line\nreplacing string\nbar\nreplacing string\nLast line"
I commented # Please note the double quotes because single quotes will escape the \n (that will become \\n). Also, you might want to think about the last line of your file since it will add \n at the end of the last line when there will not have one at the end of your original file. If you don't want that you could make something like :
f = File.open("file.txt", "r")
a = f.map do |l|
(l.include? 'foo') ? "replacing string\n" : l
end
a[-1] = a[-1][0..-2] if a[-1] == "replacing string\n"
p a.join('')
I have a file ImageContainer.xml with text as follow:
<leftArrowImage>/apps/mcaui/PAL/Arrows/C0004OptionNavArrowLeft.png</leftArrowImage>
<rightArrowImage>/apps/mcaui/PAL/Arrows/C0003OptionNavArrowRight.png</rightArrowImage>
Now, I am searching for C0004OptionNavArrowLeft.png and C0003OptionNavArrowRight.png in that file.
Code is:
#LangFileName = "ZZZPNG.txt"
fileLangInput = File.open(#LangFileName)
fileLangInput.each_line do |varStrTextSearch|
puts "\nSearching ==>" + varStrTextSearch
Dir.glob("**/*.*") do |file_name|
fileSdfInput = File.open(file_name)
fileSdfInput.each_line do |line|
if line.include?"#{varStrTextSearch}"
puts"Found"
end
end
end
end
here varStrTextSearch is string variable having different string values.
Problem is that is it is finding C0004OptionNavArrowLeft.png but not finding C0003OptionNavArrowRight.png.
Can someone tell me where I am doing wrong?
My guess is, newline chars are the problem.
fileLangInput.each_line do |varStrTextSearch|
varStrTextSearch here will contain a \n char at the end. And if your XML is not consistently formatted (for example, like this)
<leftArrowImage>
/apps/mcaui/PAL/Arrows/C0004OptionNavArrowLeft.png
</leftArrowImage>
<rightArrowImage>/apps/mcaui/PAL/Arrows/C0003OptionNavArrowRight.png</rightArrowImage>
Then your problem can be reproduced (there's no newline char after "C0003OptionNavArrowRight", so it can't be found).
Solution? Remove the unwanted whitespace.
fileSdfInput.each_line do |line|
if line.include? varStrTextSearch.chomp # read the docs on String#chomp
puts"Found"
end
end
is it possible to do something like this?
File.open('/etc/logo', 'r') do |f|
f.each_line{ |line| puts line }
end
But I don't want the content of lines to be printed as text but rather figured out as arguments to the puts command. To make myself clear, this is the example /etc/logo:
"\e[34m" + 'BLUE COLOR' + "\e[31m" + 'RED COLOR'
I want to separate the ASCII logo from my code. Thank you for your ideas.
File.open('/etc/logo', 'r') do |f|
f.each_line{ |line| eval "puts #{line}" }
end
Don't let anyone edit that file.
If you want a more secure way to do it, try this:
File.open('/etc/logo', 'r') do |f|
f.each_line{ |line|
puts line.gsub(/\\e/, "\e")
}
end
For this, you should use a file like:
\e[34mBLUE COLOR\e[31mRED COLOR
This just replaces the escaped \e with the real character.
Good afternoon!
I am pretty new to Ruby and want to code a basic search and replace function in Ruby.
When you call the function, you can pass parameters (search pattern, replacing word).
This works like this: multiedit(pattern1, replacement1, pattern2, replacement2, ...)
Now, I want my function to read a text file, search for pattern1 and replace it with replacement2, search for pattern2 and replace it with replacement2 and so on. Finally, the altered text should be written to another text file.
I've tried to do this with a until loop, but all I get is that only the very first pattern is replaced while all the following patterns are ignored (in this example, only apple is replaced with fruit). I think the problem is that I always reread the original unaltered text? But I can't figure out a solution. Can you help me? Calling the function the way I am doing it is important for me.
def multiedit(*_patterns)
return puts "Number of search patterns does not match number of replacement strings!" if (_patterns.length % 2 > 0)
f = File.open("1.txt", "r")
g = File.open("2.txt", "w")
i = 0
until i >= _patterns.length do
f.each_line {|line|
output = line.sub(_patterns[i], _patterns[i+1])
g.puts output
}
i+=2
end
f.close
g.close
end
multiedit("apple", "fruit", "tomato", "veggie", "steak", "meat")
Can you help me out?
Thank you very much in advance!
Regards
Your loop was kind of inside-out ... do this instead ...
f.each_line do |line|
_patterns.each_slice 2 do |a, b|
line.sub! a, b
end
g.puts line
end
Perhaps the most efficient way to evaluate all the patterns for every line is to build a single regexp from all the search patterns and use the hash replacement form of String#gsub
def multiedit *patterns
raise ArgumentError, "Number of search patterns does not match number of replacement strings!" if (_patterns.length % 2 != 0)
replacements = Hash[ *patterns ].
regexp = Regexp.new replacements.keys.map {|k| Regexp.quote(k) }.join('|')
File.open("2.txt", "w") do |out|
IO.foreach("1.txt") do |line|
out.puts line.gsub regexp, replacements
end
end
end
Easier and better method is to use erb.
http://apidock.com/ruby/ERB