Inserts a line into a file after a line matching a regular expression. String comparisons are case-insensitive. Works on very large files because it reads the file line by line instead of reading the entire file into memory.
Can be used on the command line or in a Ruby program.
$ gem install insert_after
Either add this line to your application’s Gemfile
:
gem 'insert_after'
... or add the following to your application’s .gemspec
:
spec.add_dependency 'insert_after'
And then execute:
$ bundle
# Inserts 'Inserted 1' after the first line containing 'line' into demo/my_file.txt:
$ insert_after line 'Inserted 1' demo/my_file.txt
# Inserts 'Inserted 1' after every line containing 'line' into demo/my_file.txt:
$ insert_after -a line 'Inserted 1' demo/my_file.txt
# Inserts an empty line after the first line containing 'line 1' into demo/my_file.txt:
$ insert_after 'line 1' '' demo/my_file.txt
# Inserts an empty line after every line containing 'line 1' into demo/my_file.txt:
$ insert_after -a 'line 1' '' demo/my_file.txt
# Inserts 'Inserted 2' after the first line starting with 'line 2' into demo/my_file.txt:
$ insert_after '^line 2' 'Inserted 2' demo/my_file.txt
# Inserts 'Inserted 2' after every line starting with 'line 2' into demo/my_file.txt:
$ insert_after -a '^line 2' 'Inserted 2' demo/my_file.txt
# Inserts 'Inserted 3' after the first line containing an 'e' followed by a '2' into demo/my_file.txt:
$ insert_after 'e.*2' 'Inserted 3' demo/my_file.txt
# Inserts 'Inserted 3' after every line containing an 'e' followed by a '2' into demo/my_file.txt:
$ insert_after -a 'e.*2' 'Inserted 3' demo/my_file.txt
The demo/demo.rb
program is an example of how to use insert_after
in a Ruby program:
require 'insert_after'
InsertAfer.insert_after 'line 2', 'New line', 'my_file.txt'
InsertAfter.insert_after 'line', 'Another line from Ruby', 'my_file.txt', all: true
After checking out this git repository, install dependencies by typing:
$ bin/setup
You should do the above before running Visual Studio Code.
$ bundle exec rspec
The following will allow you to experiment:
$ bin/console
To install this gem onto your local machine, type:
$ bundle exec rake install
To create a git tag for the new version, push git commits and tags, and push the new version of the gem to https://rubygems.org, type:
$ bundle exec rake release
Bug reports and pull requests are welcome at https://github.com/mslinn/insert_after.
The gem is available as open source under the terms of the MIT License.