我试图在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
我认为添加一些样本数据和预期的输出会很有帮助。并解释"这段代码不起作用"的含义。
我想你把文件名放在下一行了?必须将\放在末尾,才能将其作为命令处理,或者将其放在同一行awk -F":" '$1 =="$search" {print $3"" $1"" $2 }' capstonedata.txt上。否则,它将作为单独的命令处理。
你要的是read search ; search=$(echo"$search" | tr '[a-z]' '[A-Z]'; ...。和awk -v srch="$search" '{ ...}。祝你好运。
如果使用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
这:read search | tr '[a-z]' '[A-Z]'不会给变量search赋值。
应该是这样的
read input
search=$( echo"$input" | tr '[a-z]' '[A-Z]' )
最好使用参数扩展进行案例修改:
read input
search=${input^^}
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