LoginSignup
0
0

Ruby芸160チャレンジ(#4)ファイル中の文字列検索(正規表現)

Last updated at Posted at 2023-12-03

この記事は何

shellgei160を通じて言語習得 Advent Calendar 2023に参加しています。

書籍「シェル芸ワンライナー160本ノック」の例題をRubyで解いてみて、Rubyの学習に役立てようとするものです。

例題はこちらのリポジトリで公開されているものに限ります。
https://github.com/shellgei/shellgei160

実行環境など

  • Docker image: ruby:3.0.2
  • 上記リポジトリをクローンした上で、リポジトリのルートディレクトリ直下にanswer-rubyディレクトリを作り、その中に解答となるファイルを作成していきます。

今回のテーマ

$ grep -l '^10$' -R | xargs rm

「10」だけ記載された行があるファイルを削除する処理です。

files = Dir.glob('.tmp/*')

files.each do |file|
  text = File.read(file)
  puts "#{file} has #{text}" if text.match?(/^10$/)
  # 今回は削除は割愛。削除するときはFile.deleteを使う?
end

所感

  • やや慣れてきたやも。readlinesした方が良い時とreadした方が良い時と、適宜使い分けていこうかな。
0
0
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
0
0