0
1

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 5 years have passed since last update.

シェルスクリプト練習(bash)-文字列の一部を抽出-

Last updated at Posted at 2018-09-02

#やりたいこと

  • 下記のようなログの終了ログの値(カッコ内一つ目)を見て、終了ログ直前のログの値を抽出したい
log.txt
[2018/08/29 10:10:11]	[INFO ]	START
[2018/08/29 10:10:12]	[INFO ]	AAA SSSSS(123456, 098765, hahahaha)
[2018/08/29 10:10:13]	[INFO ]	END(0, GOOD)
[2018/08/30 10:10:11]	[INFO ]	START
[2018/08/30 10:10:12]	[INFO ]	BAD JOB
[2018/08/30 10:10:13]	[INFO ]	END(1, BAD)
[2018/08/31 10:10:11]	[INFO ]	START
[2018/08/31 10:10:12]	[INFO ]	AAA SSSSS(123456, 098765, hahahaha)
[2018/08/31 10:10:13]	[INFO ]	END(0, GOOD)

#やった内容

readfile.sh
#!/bin/bash -u
LINENUM=0 # 開始行
COMMAND=`tail -n +$LINENUM log.txt`
LINEDATA="" #1行分
FIRSTROW=true #開始行フラグ
while read line; do
    if ${FIRSTROW}; then
        LINEDATA=${line}
        FIRSTROW=false
        continue
    fi

    if [[ $line =~ START ]]; then
        # 開始ログの行は何もしない
        continue
    elif [[ $line =~ END ]]; then
        # 終了ログ
        result=$(echo ${line} | sed -e "s/^.*(\(.*\))/\1/g" | cut -d ',' -f 1) #カッコ内を抽出しカンマ区切りの一つ目を取得
        if [[ $result == 0 ]]; then
            IFS_ORIGINAL=${IFS}
            IFS=, # 環境変数の区切り文字をカンマに変更
            columns=$(echo ${LINEDATA} | sed -e "s/^.*(\(.*\))/\1/g") # カンマ区切りを代入するとそのまま配列扱いに
            IFS=${IFS_ORIGINAL} # 環境変数IFSを元々の区切り文字に戻す
            for v in ${columns[@]}; do
                echo -n ${v}\;
            done
            echo
        fi
    else
        # 開始終了ログのどちらでもなければ行を変数に代入
        LINEDATA=${line}
    fi

done << EOF
   ${COMMAND}
EOF
  • 開始行は都度変えるようにしたいので変数に
  • 開始終了ログに挟まれたログのカッコ内の文字を抽出する
  • 抽出したカッコ内の文字はカンマ区切りなので、分割して配列へ

ひとまずはこんなくらいか。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?