Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

ファイル内の指定文字列で始まる行の削除

概要

指定文字列で始まる行の削除について

仕様

・指定フォルダにある特定の名前を含むファイルが対象
・各ファイル内に「three」で始まる行があればその行を削除
・結果を元ファイル名+「_output.txt」で出力

コード

# encoding: Windows-31J

OUTPUT_FILE = "_output"
TARGET_FILE = "./sample*"
EXTENSION = ".txt"
SEARCH_WORD = /^three/

# 出力済みファイルがある場合削除する
Dir::glob("./*#{OUTPUT_FILE}#{EXTENSION}").each {|delete_file_name|
  File.delete(delete_file_name)
}

Dir::glob("#{TARGET_FILE}#{EXTENSION}").each {|file_name|
  file = File.open(file_name)
  output_file=open(file_name.sub(EXTENSION, "#{OUTPUT_FILE}#{EXTENSION}"),"w")
  while line_text = file.gets do
    next if SEARCH_WORD =~ line_text
    output_file.puts line_text
  end
  output_file.close
  file.close
}

対象ファイル

sample1.txt

one
two
three
four three
five

sample2.txt

one hoge
two hoge 
three hoge
four three hoge
five hoge

出力ファイル

sample1_output.txt

one
two
four three
five

sample2_output.txt

one hoge
two hoge 
four three hoge
five hoge
補足

Dir::glob("指定文字列"):指定文字列を含むファイルをリストで取得
SEARCH_WORD =~ line_text:検索ワードで行文字列をパターンマッチ