我正在尝试在Unix中创建一个程序来访问数据文件,在文件中添加,删除和搜索名称和用户名。使用这个if语句,我试图允许用户通过第一个字段搜索文件中的数据。
文件中的所有数据都使用大写字母,因此我首先必须将用户输入的任何文本从小写字母转换为大写字母。出于某种原因,此代码不能同时转换为大写并搜索和打印数据。
我该如何解决?
if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
tput cup 3 12
echo "Enter the first name of the user you would like to search for: "
tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
echo "$search"
awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }'
capstonedata.txt
fi
答案 0 :(得分:3)
这:read search | tr '[a-z]' '[A-Z]'
不会将任何内容分配给变量search
。
应该是
read input
search=$( echo "$input" | tr '[a-z]' '[A-Z]' )
最好使用case modification的参数展开:
read input
search=${input^^}
答案 1 :(得分:3)
如果使用Bash,则可以声明变量以转换为大写:
$ declare -u search
$ read search <<< 'lowercase'
$ echo "$search"
LOWERCASE
至于您的代码,read
没有任何输出,因此tr
的管道无法执行任何操作,并且您无法在awk语句中的文件名。
编辑的代码版本,减去所有tput
内容:
# [[ ]] to enable pattern matching, no need to quote here
if [[ $choice = [Ss] ]]; then
# Declare uppercase variable
declare -u search
# Read with prompt
read -p "Enter the first name of the user you would like to search for: " search
echo "$search"
# Proper way of getting variable into awk
awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
fi
或者,如果您只想使用POSIX shell结构:
case $choice in
[Ss] )
printf 'Enter the first name of the user you would like to search for: '
read input
search=$(echo "$input" | tr '[[:lower:]]' '[[:upper:]]')
awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
;;
esac
答案 2 :(得分:1)
awk不是shell(谷歌那个)。只是做:
if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
read search
echo "$search"
awk -F':' -v srch="$search" '$1 == toupper(srch) {print $3, $1, $2}' capstonedata.txt
fi