Ruby Regex Gsub a Line in a Text File

Ruby regex matching a line in an inputted text file string

string = "test\r\nfoo\r\ntest\r\nbar"
string = string.gsub(/^test(?=\r?\n)/, 'X\&X').delete(?\r)
puts string

Ruby: How to replace text in a file?

There is no possibility to modify a file content in one step (at least none I know, when the file size would change).
You have to read the file and store the modified text in another file.

replace="100"
infile = "xmlfile_in"
outfile = "xmlfile_out"
File.open(outfile, 'w') do |out|
out << File.open(infile).read.gsub(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")
end

Or you read the file content to memory and afterwords you overwrite the file with the modified content:

replace="100"
filename = "xmlfile_in"
outdata = File.read(filename).gsub(/<appId>\d+<\/appId>/, "<appId>#{replace}</appId>")

File.open(filename, 'w') do |out|
out << outdata
end

(Hope it works, the code is not tested)

How to use gsub to simplify regular expressions

Except if one or several of the urls contained inside \href{..}s has a password part enclosed between quotes like http://username:"sdkfj#lkn#"@domainname.org/path/file.ext, the only possible place for the character # in a url is at the end and delimits the fragment part: ./path/path/file.rb?val=toto#thefragmentpart.

In other words, if I am not wrong there's max one # to escape per href{...}. Then you can simply do that:

text.gsub(/\\href{[^#}]*\K#/, "\\#")

The character class [^#}] forbids the character } and ensures that you are always between curly brackets.

Ruby: sub/gsub at a particular line OR before/after a pattern

Here is the answer.

File.open("file.txt", "r").each_line do |line|
if line =~ /minor mistakes/
puts "Hello, how are you ?"
end
puts "#{line}"
end

Here is ruby one-liner.

ruby -pe 'puts "Hello, how are you ?" if $_ =~ /minor mistakes/' < file.txt

Using gsub in certain paragraphs of the text

string = File.read(file)

splited_strings = string.split(/(?=[<>])/)
splited_strings.each do |substring|
# means it's out of tag
if substring.include?(">")
substring.gsub!(/text/, "whatever")
end
end

new_str = splited_strings.join("")

Why is there an extra blank line after using gsub on file in Ruby with Thor?

For your method my_gsub you are replacing the content of the line without replacing the linebreak. To make it remove the newline as well you can change your regex to this:

gsub_file(full_app_gemfile_path, /^\s*gem\s*("|')byebug.*$\n/, "")
gsub_file(full_app_gemfile_path, /^\s*#.*Call.*("|')byebug("|').*$\n/, "")


Related Topics



Leave a reply



Submit