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

#パイプ(`|`)と `grep` の変数代入

0
Posted at

パイプ(|)と grep の変数代入

シェルスクリプトでよく使う パイプ と、grep の結果を 変数 に代入する方法をまとめています。


パイプ(|)の使い方

左側コマンドの標準出力を右側コマンドの標準入力に渡す パイプ

ls -l /var/log | grep '\.log'
  1. ls -l /var/log の出力を
  2. |grep '\.log' に渡し、
  3. .log を含む行だけを表示

複数パイプの連結

cat access.log \
  | grep 'ERROR' \
  | awk '{print $1, $4}' \
  | sort | uniq -c
  • catgrepawksortuniq の順にデータを加工

&&|| の違い

  • command1 && command2
    • command1 が成功したときだけ command2 を実行
  • command1 || command2
    • command1 が失敗したときだけ command2 を実行
grep -Fxq "/usr/sbin/nologin" /etc/shells \
  || echo "/usr/sbin/nologin" | sudo tee -a /etc/shells

grep の結果を変数に代入する方法

1. 行全体を取得

#!/bin/bash
# ファイルから“ERROR”を含む最初の行だけを取得
error_line=$(grep -m1 'ERROR' /path/to/logfile.log)
echo "エラー行: $error_line"
  • $( … ) がコマンド置換。
  • -m1 で最初の1行のみ取得。

2. 部分文字列だけを取得

#!/bin/bash
# “ユーザーID:12345” の数字部分だけを抽出
user_id=$(grep -oP '(?<=ユーザーID:)\d+' sample.txt)
echo "ユーザーID = $user_id"
  • -o:マッチ部分だけ出力
  • -P:Perl互換正規表現
  • (?<=…)(?=…):lookaround

3. sedawk と組み合わせて取得

#!/bin/bash
# CSV の 3 列目だけを取得
col3=$(grep 'pattern' sample.csv | awk -F',' '{print $3}' | head -n1)
echo "3列目: $col3"
#!/bin/bash
# `key=value` の value 部分だけを取得
value=$(grep 'key=' config.ini | sed -E 's/.*key=([^;]+).*//' | head -n1)
echo "設定値: $value"

4. 複数行を配列に格納

#!/bin/bash
# 全WARN行を warnings 配列に格納
mapfile -t warnings < <(grep 'WARN' /path/to/log.log)
# 配列ループ
for w in "${warnings[@]}"; do
  echo "警告: $w"
done
# 先頭要素だけ
first_warn=${warnings[0]}
echo "最初の警告: $first_warn"

5. 注意点

  1. マッチなし → 空文字列
    • set -u と組み合わせる場合は未定義変数に注意。
  2. 改行を含む場合
    • 変数に改行を含めたくないときは tr -d ' ' などで除去。
  3. パターン・ファイル名のクォート
    • エスケープやスペースに注意し、クォートを忘れずに。

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