![查找以用户在指定文件中输入的字母开头的单词 - bash](https://linux22.com/image/180661/%E6%9F%A5%E6%89%BE%E4%BB%A5%E7%94%A8%E6%88%B7%E5%9C%A8%E6%8C%87%E5%AE%9A%E6%96%87%E4%BB%B6%E4%B8%AD%E8%BE%93%E5%85%A5%E7%9A%84%E5%AD%97%E6%AF%8D%E5%BC%80%E5%A4%B4%E7%9A%84%E5%8D%95%E8%AF%8D%20-%20bash.png)
我想创建 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:]]