Skip to content

Instantly share code, notes, and snippets.

@sizer
Last active September 23, 2015 06:08
Show Gist options
  • Save sizer/87b6d43be2eb0d55aa95 to your computer and use it in GitHub Desktop.
Save sizer/87b6d43be2eb0d55aa95 to your computer and use it in GitHub Desktop.
Read and grep csv by ruby
FILE_NAME = ARGV[0]
KEYWORD = ARGV[1]
SPLITTER = /,/
def howto
puts "Howto? " + File.basename($0) + " <filename>" + " <keyword>"
end
# 引数が想定しないパターンの場合にエラー表示。
if ARGV.empty? || ARGV.count() != 2
howto()
end
# ファイルが存在する場合、各行を要素ごとに分割した後、キーワードを検索。
# キーワードに一致する要素が存在する場合、標準出力を行う。
if File.exist?(FILE_NAME)
count = 0
File.readlines(FILE_NAME).each do |line|
line.split(SPLITTER).each do |word|
word.chomp!
if word.include?(KEYWORD)
count += 1
puts line
end
end
end
puts count.to_s + "lines in " + FILE_NAME + " \"" + KEYWORD + "\""
else
puts FILE_NAME + " file not found."
end
@sizer
Copy link
Author

sizer commented Sep 23, 2015

update last column cannot match

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment