4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Bash]対象パターンの行数をカウントする

Last updated at Posted at 2021-02-23

Bashで、対象パターンの行数をカウントするサンプルコード(覚え書き)。
具体的には、ファイル内に、対象文字列が所定の箇所にある行数をカウントします。

環境

  • OS: Amazon Linux2

概要

指定したファイル内に、対象文字列が所定の箇所にある行数をカウントします。

コマンドライン引数の
第1引数: ファイル名
第2引数: 検索したい文字列
第3引数: 切り取り開始位置(行の先頭が0始まり)
第4引数:切り取り数
を指定して実行します。

コード

count_match_line.sh
# !/bin/bash
#
# 対象文字列が所定の箇所にある行数をカウント
#
# $1: ファイル名
# $2: 検索したい文字列
# $3: 切り取り開始位置(行の先頭を0として)
# $4: 切り取り数

count=0
while read line
do
   if [ ${line:${3}:${4}} = $2 ] ; then
        count=$((count+1))
   fi
done < $1

echo "対象データは$count件です"

本当は、

count=$((count++))

にしたかったけど、うまくいかなかったので、

count=$((count+1))

にしました(解決したら直します)。

実行してみる

以下のファイルで、各行の先頭を0文字目として、13文字目~が、123となっている行数をカウントします。

hoge.tsv
000000  00000   123     000001
000000  00000   125     000001
000000  00000   124     000001
000000  00000   123     000002
000000  00000   123     000003
000000  00000   124     000002
000000  00000   123     000004
000000  00000   125     000002

1, 4, 5, 7行目の計4行に、123が含まれています。
スペースっぽい箇所は、タブです。

実行コマンドと結果

$ bash count_match_line.sh /product/share/eee/hoge.tsv 123 13 3
対象データは4 件です

うまくいきました!

参考

4
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
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?