LoginSignup
8

More than 5 years have passed since last update.

posted at

updated at

Organization

ファイルの中にある特定文字列を数える

Linux上のとあるファイルの中から特定の文字列が何個含まれてるか

状況例

hoge.txt
hogefugapiyohogefugapiyo
hogehogehogehogehogehoge

みたいなファイルから「hoge」の数を知りたい時。
(ちなみに 8 こ)

ビルトインのコマンドで何とか出現回数を調べようと思ったのですが、上手く行かなかったのでPythonでスクリプト書いてみました。
(grepだと一行に複数回の出現に対応できなかったりするので)

特定文字列の数を計算するスクリプト

match_count.py
# -*- coding: utf-8 -*-
#!/usr/bin/env python

import sys
import os.path


def clean_args(args):
    if len(args) == 2:
        search_word = args[1] 
        return (True, None, search_word)
    if len(args) != 3: 
        print "[Usage] match_count.py $filename $search_word"
        return (False, None, None)

    target_file_path = args[1]
    search_word       = args[2] 

    if not os.path.exists(target_file_path):
        print "[Error] File is not exist."
        return (False, None, None)

    return (True, target_file_path, search_word)


def count_words(filename, search_word):

    if filename is not None:
        # python 2.4だったのでwith使えず
        stream = open(filename, 'r')
        counter = _count(stream, search_word)
        stream.close()
        return counter
    else :
        return _count(sys.stdin, search_word)


def _count(stream, search_word):
    counter = 0
    for line in stream:
        counter += line.count(search_word)
    return counter


def main():

    args = sys.argv
    (is_valid, filename, search_word) = clean_args(args)
    if not is_valid:
        sys.exit()

    print count_words(filename, search_word)


if __name__ == '__main__':
    main()

このファイルをLinux上で作って、実行権限をつけます。

使い方

$ ./match_count.py hoge.txt hoge
8

みたいな感じでhogeにマッチした数を取得できます。

パイプにも対応してみたので

$ cat hoge.txt | ./match_count.py hoge
8

みたいにしても使えます。
複数ファイルをcatしたりすれば捗るかな。

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
What you can do with signing up
8