1
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 1 year has passed since last update.

bashでテキストファイルで特定文字列を含む行を抽出する

Posted at

はじめに

テキストファイルやエクセルで作成されたタスク管理表を自分で見るためにbashの特定文字列を含む行の抽出方法を調べた。

抽出方法

上記の内容を実現するために以下の二つを調べた。

テキストファイルを1行ずつ読み込む方法

catしたものをパイプでwhile read lineと書くことで一行ずつ処理が可能になる。

cat {filename} | while read line
do
    # $lineに対して具体的な処理
done

特定文字を含むかどうか判定する方法

ここに関してはいろいろな方法があると思いますが、私はif文で以下のような方法を選びました。

# やり方1
if [[ "$line" == *ToDo* ]]; then
    # ToDoを含むときの処理
else
    # ToDoを含まない時の処理
fi

# やり方2
if [[ "$line" =~ "ToDo" ]]; then
    # ToDoを含むときの処理
else
    # ToDoを含まない時の処理
fi

実際の実装

今回は、テキストファイル内のToDoを含む行のみを抽出したかったため、以下のようにテキストファイルの処理を行いました。

cat {filename} | while read line
do
    if [[ "$line" == *ToDo* ]]; then
        echo $line
    fi
done > todolist

さいごに

bashは調べてみるといろいろと便利に使えるのですごく多機能だと感心します。業務の合間に少しずつ慣れていきたいなと思います。

参考

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