繰り返されるgrepコマンドを別々のファイルにリダイレクトする

繰り返されるgrepコマンドを別々のファイルにリダイレクトする

grepを使用してファイルにリストされているパターンを使用してディレクトリを再帰的に検索し、後で参照できるように各結果を独自のファイルに保存したいと思います。

私(使用してこの問題指示として)以下を提案します。

#!/bin/bash

mkdir -p grep_results   # For storing results

echo "Performing grep searches.."
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Seaching for $line.."
    grep -r "$line" --exclude-dir=grep_results . > ./grep_results/"$line"_infile.txt
done

echo "Done."

ただし、実行すると CTRL-C を押すまでコンソールが停止します。

$ bash grep_search.sh search_terms.txt
Performing grep searches..

このスクリプトの問題は何ですか?それとも私が間違っているのでしょうか?

ベストアンサー1

ここにはいくつかの質問があります。

  1. ループはwhile入力を読みません。正しい形式は次のとおりです。

    while read line; do ... ; done < input file
    

    または

    some other command | while read ...
    

    したがって、ループが停止して入力を待ちます。スクリプトを実行して何も入力し、Enterキーを押してそれをテストできます(ここでは入力しましたfoo)。

    $ foo.sh 
    Performing grep searches..
    foo
    Searching for foo..
    

    次にヒントを追加してこれを改善できますread

    while IFS='' read -p "Enter a search pattern: " -r line ...
    

    Ctrlただし、+を使用して停止するまで実行され続けますC

  2. (つまり|| [[ -n "$line" ]]、「または$line変数が空ではない」という意味)は決して実行されません。中断のため、read「OR」は到着しません。とにかく、私はあなたが何をしたいのか理解していません。定義されている$line場合は検索し、定義されていない場合は使用するには次のものが必要です。$lineread

    if [[ -n "$line" ]]; then
         grep -r "$line" --exclude-dir=grep_results > ./grep_results/"$line"_infile.txt
    else
        while IFS='' read -p "Enter a search pattern: " -r line || [[ -n "$line" ]]; do
          grep -r "$line" --exclude-dir=grep_results > ./grep_results/"$line"_infile.txt
        done
    fi
    

    ここで$line定義されていない場合でも、手動で入力する必要があります。よりきれいな方法は、ファイルをループに供給することですwhile

    while IFS='' read -r line || [[ -n "$line" ]]; do
      grep -r "$line" --exclude-dir=grep_results > ./grep_results/"$line"_infile.txt
    done < list_of_patterns.txt
    

おすすめ記事