Converting user input to uppercase
我试图在Unix中创建一个访问数据文件的程序,在文件中添加、删除和搜索名称和用户名。使用这个if语句,我试图允许用户按第一个字段搜索文件中的数据。
文件中的所有数据都使用大写字母,因此我首先必须将用户输入的任何文本从小写字母转换为大写字母。出于某种原因,此代码不适用于转换为大写以及搜索和打印数据。
我怎么修?
1 2 3 4 5 6 7 8 | 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 |
如果使用bash,则可以声明要转换为大写的变量:
1 2 3 4 | $ declare -u search $ read search <<< 'lowercase' $ echo"$search" LOWERCASE |
至于您的代码,
代码的编辑版本,减去所有
1 2 3 4 5 6 7 8 9 10 11 12 13 | # [[ ]] 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构造:
1 2 3 4 5 6 7 8 | 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 |
这:
应该是这样的
1 2 | read input search=$( echo"$input" | tr '[a-z]' '[A-Z]' ) |
最好使用参数扩展进行案例修改:
1 2 | read input search=${input^^} |
awk不是shell(谷歌那个)。只做:
1 2 3 4 5 | 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 |