ログファイルで文字列を検索するシェルスクリプト

ログファイルで文字列を検索するシェルスクリプト

次のように、複数のログファイルのディレクトリ文字列を一致させるスクリプトがあります。

#!/bin/sh
# Collect Customer ID as input
read -p "Enter Customer ID: " custid
echo "Searched customer ID $custid found in following logs: "
# Find the customer id as string in specified directory
find /usr/local/tomcat9/logs/ -type f -exec grep -l "$custid" {} \;

これにより、検索文字列を含むログファイルのリストが出力されます。たとえば、

Enter Customer ID: 2001NM-100313
Searched customer ID 2001NM-100313 found in following logs:
/usr/local/tomcat9/logs/localhost_access_log.2017-10-04.txt
/usr/local/tomcat9/logs/localhost_access_log.2017-07-11.txt
/usr/local/tomcat9/logs/localhost_access_log.2017-11-02.txt
/usr/local/tomcat9/logs/localhost_access_log.2017-09-11.txt
/usr/local/tomcat9/logs/localhost_access_log.2017-08-09.txt
/usr/local/tomcat9/logs/localhost_access_log.2017-06-11.txt

この出力を次のリストにしたいと思います。

1. /usr/local/tomcat9/logs/localhost_access_log.2017-10-04.txt
2. /usr/local/tomcat9/logs/localhost_access_log.2017-07-11.txt
3. /usr/local/tomcat9/logs/localhost_access_log.2017-11-02.txt
4. /usr/local/tomcat9/logs/localhost_access_log.2017-09-11.txt
5. /usr/local/tomcat9/logs/localhost_access_log.2017-08-09.txt
6. /usr/local/tomcat9/logs/localhost_access_log.2017-06-11.txt

1/2/3/4/5/6という数字を入力すると、その数字のファイルが開きます。つまり、4を押すとコマンドが送信されます。

vim /usr/local/tomcat9/logs/localhost_access_log.2017-09-11.txt

そして、ファイル全体で「2001NM-100313」文字列が検索されます。

私の目標は、ログファイルからこの文字列を含む行全体を読み取ることです(文字列を含む複数行がある可能性があります)。この文字列と複数の日付を含む複数のログファイルがあります。日付ファイルのある項目を選択して読み取る必要があります。日誌。

ベストアンサー1

ただselectbash組み込み)を使用してください。

$ help select
select: select NAME [in WORDS ... ;] do COMMANDS; done
    The WORDS are expanded, generating a list of words.  The
    set of expanded words is printed on the standard error, each
    preceded by a number.  If `in WORDS' is not present, `in "$@"'
    is assumed.  The PS3 prompt is then displayed and a line read
    from the standard input.  If the line consists of the number
    corresponding to one of the displayed words, then NAME is set
    to that word.  If the line is empty, WORDS and the prompt are
    redisplayed.  If EOF is read, the command completes.  Any other
    value read causes NAME to be set to null.  The line read is saved
    in the variable REPLY.  COMMANDS are executed after each selection
    until a break command is executed.
$

したがって、必要なコードは次のようになります。

read -p 'Enter Customer ID: ' custid
select f in $(find /usr/local/tomcat9/logs -type f -exec grep -q -e "$custid" {} \; -print); do
  vim "$f"
done

ファイル名にスペースが含まれていると中断されます。また見なさい:


ただし、select組み込み関数を直接呼び出すと、findスペースを簡単に処理できます。だから実は下が良いすべてのケースで私は次のことを考えることができます。

read -p 'Enter customer ID: ' custid
find /usr/local/tomcat9/logs -type f -exec grep -qe "$custid" {} \; -exec bash -c '
  select f; do vim "$f"; done' find-sh {} +

おすすめ記事