LoginSignup
9
9

More than 5 years have passed since last update.

ファイル内の正規表現でマッチした行を表示

Posted at

久しぶりにRubyのプログラムを書きました。
コマンドラインでファイル名と正規表現を入力すると、ファイル内の正規表現にマッチした行を表示するプログラムです。
プログラムは下のようになります。

matchput.rb
filename = ARGV[0]
word = /#{ARGV[1]}/

File.open(filename, "r") do |file|
  file.each_line do |line|
    puts line if line =~ word
  end
end

2行目で第二引数に入力された文字列を正規表現に変換しています。
あとはファイルを読み込み専用で開き、6行目で正規表現にマッチした行を表示しています。
実行結果を下に示します。

file.txt
I love Ruby.
Ruby is very cool.
実行結果
$ ruby matchput.rb file.txt ^Ruby
Ruby is very cool.

実行速度に問題があるかもしれません。
こういうプログラムを簡単に書けるのがRubyの良い所ですね。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9