查找以用户在指定文件中输入的字母开头的单词 - 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

编辑名称.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]or 。$name == [[:alpha:]]

相关内容