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?

AWS S3 ファイル本文からGREP検索する方法

Last updated at Posted at 2025-08-27

AWS CloudShell などで実行可能です

単一ファイルから検索する場合

S3_BUCKET=your-s3-bucket-name
S3_KEY_PREFIX=your-directory-name/
FILE_NAME='index.html'
GREP_KEYWORD='keyword'

aws s3 cp s3://${S3_BUCKET}/${S3_KEY_PREFIX}${FILE_NAME} - | grep -q ${GREP_KEYWORD};

複数ファイルから検索する場合

一度、ファイルをcpコマンドで標準出力にダウンロードするため、時間がかかります。

GREP検索 下準備

# 変数を定義
S3_BUCKET=your-s3-bucket-name
S3_KEY_PREFIX=your-directory-name/
GREP_KEYWORD='keyword'
FILE_EXTENSION='.html'

# ループ時に Ctrl + C を入力された際に即時終了するようにtrapしておく。
trap 'exit' 2

# ファイル名のリストを取得
S3_KEY_LIST=`aws s3api list-objects-v2 --bucket ${S3_BUCKET} --prefix ${S3_KEY_PREFIX} --query "Contents[?ends_with(Key, '${FILE_EXTENSION}')].Key" --output text`

# ファイル名のリストが意図した通りか念のため確認
printf "%s\n" $S3_KEY_LIST

GREP検索 実行

# 検索対象のファイルでループ処理開始
for s3_key in ${S3_KEY_LIST}; do
  # 標準出力にダウンロードしてファイル本文を出力し、GREPをかける
  if aws s3 cp s3://${S3_BUCKET}/${s3_key} - | grep -q ${GREP_KEYWORD}; then
    echo "Found in: ${s3_key}"
  fi
done

ファイル名からGREP検索する方法

S3_BUCKET=your-s3-bucket-name
GREP_KEYWORD='filename.txt'

aws s3 ls s3://${S3_BUCKET} --recursive | grep ${GREP_KEYWORD}
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?