linux declare大小写,关于linux:将用户输入转换为大写
我試圖在Unix中創(chuàng)建一個(gè)訪問(wèn)數(shù)據(jù)文件的程序,在文件中添加、刪除和搜索名稱和用戶名。使用這個(gè)if語(yǔ)句,我試圖允許用戶按第一個(gè)字段搜索文件中的數(shù)據(jù)。
文件中的所有數(shù)據(jù)都使用大寫(xiě)字母,因此我首先必須將用戶輸入的任何文本從小寫(xiě)字母轉(zhuǎn)換為大寫(xiě)字母。出于某種原因,此代碼不適用于轉(zhuǎn)換為大寫(xiě)以及搜索和打印數(shù)據(jù)。
我怎么修?
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
我認(rèn)為添加一些樣本數(shù)據(jù)和預(yù)期的輸出會(huì)很有幫助。并解釋"這段代碼不起作用"的含義。
我想你把文件名放在下一行了?必須將\放在末尾,才能將其作為命令處理,或者將其放在同一行awk -F":" '$1 =="$search" {print $3"" $1"" $2 }' capstonedata.txt上。否則,它將作為單獨(dú)的命令處理。
你要的是read search ; search=$(echo"$search" | tr '[a-z]' '[A-Z]'; ...。和awk -v srch="$search" '{ ...}。祝你好運(yùn)。
如果使用bash,則可以聲明要轉(zhuǎn)換為大寫(xiě)的變量:
$ declare -u search
$ read search <<< 'lowercase'
$ echo"$search"
LOWERCASE
至于您的代碼,read沒(méi)有任何輸出,因此管道到tr沒(méi)有任何作用,并且在awk語(yǔ)句中的文件名之前不能有新行。
代碼的編輯版本,減去所有tput的內(nèi)容:
# [[ ]] 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構(gòu)造:
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]'不會(huì)給變量search賦值。
應(yīng)該是這樣的
read input
search=$( echo"$input" | tr '[a-z]' '[A-Z]' )
最好使用參數(shù)擴(kuò)展進(jìn)行案例修改:
read input
search=${input^^}
awk不是shell(谷歌那個(gè))。只做:
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
總結(jié)
以上是生活随笔為你收集整理的linux declare大小写,关于linux:将用户输入转换为大写的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux安装autossh详细教程,在
- 下一篇: linux中atoi函数的实现 值得借鉴