LoginSignup
0
0

シェルスクリプトでファイル内の特定パターン間の文字列検索

Posted at

ファイル内の特定のパターンに基づいて特定の文字列を検索するタスクは、システム管理や開発作業中によく遭遇するシナリオです。今回は、const static hoge_というパターンで始まる行を見つけ、これらの行間に存在する指定された文字列を検索するシェルスクリプトを作成する方法を紹介します。

このスクリプトは特に、ファイルの特定の範囲をユーザーが対話的に選択し、その範囲内で文字列を検索する機能を提供します。また、スクリプトの最後にはファイルの終わりまでを含むように設計されています。

スクリプトの概要

  1. パターンマッチング:まず、grepを使用してconst static hoge_で始まる行を検出します。
  2. ユーザー入力:ユーザーがどの範囲を検索したいかを選べるようにします。
  3. 文字列検索:選択された範囲内でgrepを使用して特定の文字列を検索します。

スクリプトの詳細

#!/bin/bash

# 検索するファイルのパス
file_path="your_file.txt"
# 特定の間に検索する文字列
search_string="target_string"

# 検索するパターン
pattern="const static hoge_"

# パターンに一致する行の番号を取得し、ファイルの最終行番号も追加
line_numbers=($(grep -n "$pattern" "$file_path" | cut -d':' -f1))
line_numbers+=($(wc -l < "$file_path"))

# パターンが見つからなかった場合の処理
if [ ${#line_numbers[@]} -le 1 ]; then
  echo "No lines found with the pattern: $pattern"
  exit 1
fi

# ユーザーに範囲の選択を促す
echo "Select the range to search the string '$search_string':"
for (( i=0; i<${#line_numbers[@]}-1; i++ )); do
  echo "$((i+1))) Between line ${line_numbers[$i]} and line ${line_numbers[$((i+1))]}"
done

# ユーザー入力を受け取る
read -p "Enter your choice (1-${#line_numbers[@]}-1): " choice

# 選択した範囲での検索処理
if [ $choice -gt 0 ] && [ $choice -le $((${#line_numbers[@]}-1)) ]; then
  start=${line_numbers[$((choice-1))]}
  end=${line_numbers[$choice]}
  range="${start},${end}p"
  if sed -n "$range" $file_path | grep -q "$search_string"; then
    echo "Found '$search_string' in the selected range."
  else
    echo "'$search_string' not found in the selected range."
  fi
else
  echo "Invalid choice. Exiting."
  exit 1
fi

まとめ

このスクリプトは、ファイル内でconst static hoge_で始まる行間を対象に特定の文字列を検索する際に役立ちます。ユーザーが範囲を対話的に選べる点と、スクリプトが簡潔である点が特徴です。データの解析やログのチェックなど、多岐にわたる用途に利用可能です。

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