指定されたファイルでユーザーが入力した文字で始まる単語を検索する - bash

指定されたファイルでユーザーが入力した文字で始まる単語を検索する - bash

指定されたファイルで、ユーザーが入力した文字で始まるすべての単語を検索する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

Edit name.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)"resultCourt of the partというコマンドを実行しようとしているため、$(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:]]

おすすめ記事