web-dev-qa-db-ja.com

Grepを使用してファイル内のパターンを検索するBashスクリプト

GREPを使用してファイル内のパターンを検索するbashスクリプトを書いています。なぜそれが機能しないのか私には無知です。これはプログラムです

echo "Enter file name...";
read fname;
echo "Enter the search pattern";
read pattern
if [ -f $fname ]; then
    result=`grep -i '$pattern' $fname`
    echo $result;
fi

またはこれを行うための別のアプローチはありますか?

ありがとう


(ファイルの内容)

Welcome to UNIX
The Shell is a command programming language that provides an interface to the UNIX operating system.
The Shell can modify the environment in which commands run.
Simple UNIX commands consist of one or more words separated by blanks. 
Most commands produce output on the standard output that is initially connected to the terminal. This output may be sent to a file by writing.
The standard output of one UNIX command may be connected to the standard input of another UNIX Command by writing the `pipe' operator, indicated by |

(パターン)

`UNIX` or `unix`

Grepステートメントの$patternを一重引用符で囲むと、シェルはシェル変数を解決しないため、二重引用符を使用する必要があります。

18
Moritz Both

それらのセミコロンの1つ(thenの前のセミコロン)だけが必要ですが、通常は省略してthenを単独で1行に記述します。エコーする変数とgrepパターンを保持する変数を二重引用符で囲む必要があります。ファイル名を保持する変数も引用符で囲む必要があります。 readにプロンプ​​トを表示させることができます。バックティックの代わりに$()を使用する必要があります。

read -p "Enter file name..." fname
read -p "Enter the search pattern" pattern
if [ -f "$fname" ]
then
    result=$(grep -i "$pattern" "$fname")
    echo "$result"
fi
4

read -p "ファイル名を入力してください..." fname read -p "検索パターンを入力してください"パターンif [-f "$ fname"] then result = $(grep -i -v -e $ pattern -e "$ fname ")echo" $ result "fi

0
user8952030