0

私は Linux を初めて使用し、プログラミングを知りません。しかし、いくつかのことを読むことで理解できるので、質問することができます.

私は以下のようなことをしています、

ファイルでいくつかの単語を見つけて、別のファイルでそれに応じてアクションを実行します。

find in log.txt
if "not found" 1 > notify.txt
if "reset by peer" 2 > notify.txt
if "Permission denied" 3 > notify.txt
if "Fetching" 0 > notify.txt
exit

お気に入り

if [it found] "not found" [text in the log.txt then it will write] 1 > notify.txt
if [it found] "reset by peer" [text in the log.txt then it will write] 2 > notify.txt
if [it found] "Permission denied" [text in the log.txt then it will write] 3 > notify.txt
if [it found] "Fetching" [text in the log.txt then it will write] 0 > notify.txt

スクリプトを書くのを手伝ってください。

notify.txt に 0 または 1 または 2 または 3 を書き込みたいとします。これで、スクリプトが何を書き込むかを決定します。スクリプトは、log.txt ファイルを読み取って決定します。

ありがとう

4

1 に答える 1

1

あなたの質問にはいくつかのあいまいさがありますが、これがあなたが探しているものだと思います:

#!/bin/bash

# Put the source file / output file in variables
# so they are easier to change
src_file=log.txt
outfile=notify.txt

# Look for the patterns in the source file with "grep":
not_found=$(grep "not found" $src_file)
reset_by_peer=$(grep "reset by peer" $src_file)
perm_denied=$(grep "Permission denied" $src_file)
fetching=$(grep "Fetching" $src_file)

# If the output file already exists, remove it
if [[ -f $outfile ]]; then
    rm -f $outfile
fi

# Create a blank output file
touch $outfile

# If any of the patterns are found, print a number accordingly:
if [[ -n $not_found ]]; then
    echo "1" >> $outfile
fi 

if [[ -n $reset_by_peer ]]; then
    echo "2" >> $outfile
fi 

if [[ -n $perm_denied ]]; then
    echo "3" >> $outfile
fi 

if [[ -n $fetching ]]; then
    echo "0" >> $outfile
fi 

if1 つのブロックではなく複数のブロックで質問を組み立てたのでif-else if-...-else、ソース ファイルに複数のパターンが存在する可能性があると想定しています。その場合、複数の数字を出力ファイルに表示する必要があります。(これは、パターンの 1 つだけが src ファイルに存在できる場合でも機能しますが)

于 2012-11-03T13:09:52.020 に答える