
指定されたファイル (スクリプトで指定するか、ユーザー入力も作成) でユーザーが入力した文字で始まるすべての単語を検索する bash スクリプトを作成したいと考えています。私は Linux の初心者ですが、コードは次のとおりです。
#! /bin/bash
echo 'Please enter starting letter of Name'
read name
result=$(awk '/$name/ {print}' /home/beka/scripts/names.txt)
echo "$(result)"
次のようなエラーが発生します:
Please enter starting letter of Name
G
/home/beka/scripts/test.sh: line 6: result: command not found
何が間違っているのでしょうか? awk の例を検索してみましたが、正確な解決策が見つかりません。 よろしくお願いします。
編集されたコード
#! /bin/bash
echo 'Please enter starting letter of Name'
read name
if [[ $name == [A-Z] ]]
then
awk "/$name/{print}" /home/beka/scripts/names.txt
else
echo '0'
fi
編集names.txtは名前のリストです
Michael
Christopher
Jessica
Matthew
Ashley
Jennifer
Joshua
別の編集
#! /bin/bash
echo 'Please enter starting letter (Uppercase) of name'
read name
if [[ $name == [A-Z] ]]
then
echo "---Names starting with $name---"
awk "/$name/{print}" /home/beka/scripts/names.txt
elif [[ $name == [a-z] ]]
then
awk "/$name/{print}" /home/beka/scripts/names.txt
else
echo '---------'
echo 'Names not found'
fi
答え1
echo "$(result)"
result
部品の礼儀としてという名前のコマンドを実行しようとしている$(result)
ため、エラー メッセージが表示されますresult: command not found
。
これを試してください(未テスト):
#!/usr/bin/env bash
result=''
while [[ -z "$result" ]]; do
echo 'Please enter starting letter of Name'
read name
if [[ $name == [A-Z] ]]
then
result=$(awk -v name="$name" 'index($0,name)==1' /home/beka/scripts/names.txt)
else
echo '0'
fi
done
echo "$result"
大文字と小文字を区別せずに検索するには:
awk -v name="$name" 'index(tolower($0),tolower(name))==1' /home/beka/scripts/names.txt
当然ながら、検索文字として小文字を受け入れられるようにしたい場合は、または$name == [A-Z]
に変更する必要もあります。$name == [a-zA-Z]
$name == [[:alpha:]]