I want to share a ruby script for how to trim a file text above a certain line number or any condition
require 'fileutils' class File_Text_Trimmer def self.trim_text(line_number) open('some.txt', 'r') do |f| open('some.txt.tmp', 'w') do |f2| f.each_line do |line| f2.write(line) unless $. < line_number # this is condition # $. < line_number end end end FileUtils.mv 'some.txt.tmp', 'somechanged.txt' # to save changes in same file or to overwrite # FileUtils.mv 'some.txt.tmp', 'some.txt' end end
In, above you can send the line_number as an argument to this method
To run on Windows 10, first install Ruby from their official site. Mostly it will be installed in C:\Ruby[version]-x[32|64].
If you have saved above script at location
D:\Ruby-Script\File_Text_Trimmer.rb
Then you can call this script like this
ruby -r "D:\Ruby-Script\File_Text_Trimmer.rb" -e "File_Text_Trimmer.trim_text 5"
One thing more some.txt file should be in same folder from where you are running above command or you can give its full absolute path.
To do, make the filename also argument base.
Thats it!