Ruby text conversion

Use Ruby to convert PHP programs. EUC_JP and CP51932 are mixed in the PHP character code. Python can't handle CP51932, so I wrote it in Ruby.

Replace str_src with str_target. If str_src is missing, nothing is done.

file_filter.rb


#! /usr/bin/ruby
# -*- coding: utf-8 -*-
#
#	file_filter.rb 
#
#						Aug/09/2020
#
#
# --------------------------------------------------------------------
# [2]:
def read_proc(file_in)
	lines = []
	File.open(file_in) do |io|
		lines = io.readlines()
	end
#
	return lines
end
#
# --------------------------------------------------------------------
# [4]:
def convert_proc(lines)
	flag_convert = false
	str_src = '$var = $dict["aa"];'
	str_target = 'if(array_key_exists("aa",$dict)){$var = $dict["aa"];}'
	llx = str_src.size

	lines_new = []
	for line in lines do
		if line.slice(0,llx) == str_src then
			puts line
			lines_new.push(str_target)
			flag_convert = true
		else
			lines_new.push(line)
		end
#
end
#
	return flag_convert,lines_new

end
# --------------------------------------------------------------------
# [6]:
def out_proc(file_out,lines_new)
	File.open(file_out, mode = "w") do |f|
		lines_new.each{ |line| f.puts(line)}
	end
	STDERR.puts	file_out + " written ***"
end
# --------------------------------------------------------------------
STDERR.puts	"*** start ***"
file_in = ARGV[0]
#
lines = read_proc(file_in)
#
flag_convert,lines_new = convert_proc(lines)
#
if flag_convert then
	out_proc(file_in,lines_new)
end
#
STDERR.puts	"*** end ***"
# --------------------------------------------------------------------

Run

./file_filter.rb in01.txt

Recommended Posts

Ruby text conversion
Ruby learning 4
JavaFX text
[Ruby] Array
Ruby basics
Ruby Review 2
Ruby addition
Refactoring Ruby
Ruby learning 3
Java-forced conversion
Ruby setting 2
Ruby problem ⑦
Ruby learning 2
[Ruby] Block
Refactoring Ruby
ruby calculator
Ruby learning 6
Ruby settings 1
Refactoring Ruby
Ruby basics
Ruby memo
Ruby learning 1
Ruby Review 1
[Ruby] Module
[Ruby Mine] {} → Disable automatic block conversion of do..end