Shell 需要帮助在找到值后回显变量吗
我的要求如下Shell 需要帮助在找到值后回显变量吗,shell,scripting,Shell,Scripting,我的要求如下 txt="Notepad" doc="Microsoft Word" xls="Microsoft Excel" pst="Microsoft Outlook" 对于文件名,我需要找到extn文件。如果extn是txt,那么我应该回显“记事本”,如果ext是xls,那么我应该回显“MicrosoftExcel” 下面是我尝试过但没有得到正确输出的代码 filename=/admin/phase1/project/summary_copy_new.txt onlyfilename
txt="Notepad"
doc="Microsoft Word"
xls="Microsoft Excel"
pst="Microsoft Outlook"
对于文件名,我需要找到extn文件。如果extn是txt,那么我应该回显“记事本”,如果ext是xls,那么我应该回显“MicrosoftExcel”
下面是我尝试过但没有得到正确输出的代码
filename=/admin/phase1/project/summary_copy_new.txt
onlyfilename=`basename $filename`
echo $onlyfilename
以summary\u copy\u new.txt格式获取答案
ext=`echo "$onlyfilename##*.}"`
echo $ext
以txt格式获取答案
现在,如果我给出以下命令,我不会得到“记事本”作为答案
echo "$""$ext"
我得到的输出是$txt。
但我需要“记事本”作为输出
有人能帮忙吗?您需要像这样调用eval命令:
eval echo "$""$ext"
此命令的输出是txt变量Notepad的内容。对于间接变量扩展,请使用
${!name}
结构。e、 g.为了
txt="Notepad"
ext="txt"
echo "${!ext}"
#Notepad
另外,“$onlyfilename##*.}”
也可以工作,如下所示:
ext="${onlyfilename##*.}"
当文件没有任何扩展名时会遇到问题,例如
file="some"
ext=${file##*.}
echo "$ext"
#some
结果显然是错误的。因此,使用正则表达式更好
应用程序的完整演示:
txt="Notepad"
doc="Microsoft Word"
xls="Microsoft Excel"
pst="Microsoft Outlook"
gz="gzip"
while read -r file
do
base=$(basename "$file")
[[ $base =~ ^([^.]*)\.(.*)$ ]] && ext=${BASH_REMATCH[2]} || ext="NOTHING"
printf "%-12s extension is: %-8s program is: %s\n" "$base" "$ext" "${!ext:-PROGRAM_UNDEFINED}"
done <<'EOF'
/some/text.txt
/spaced dir/excel.xls
/spacedname/e mail.pst
/undefinedext/word.docx
/multidot/file.tar.gz
/no/extension
EOF
上面的问题是,您不能定义一个程序,例如,tar.gz
,因为您不能用点定义变量:tar.gz=“tar”
因此(以及许多其他原因)最好使用关联数组
declare -A prg_for=(
[txt]="Notepad"
[doc]="Microsoft Word"
[xls]="Microsoft Excel"
[pst]="Microsoft Outlook"
[gz]="gzip"
[tar.gz]="tar"
)
while read -r file
do
base=$(basename "$file")
[[ $base =~ ^([^.]*)\.(.*)$ ]] && ext=${BASH_REMATCH[2]} || ext="NOTHING"
printf "extension is: %10s program is: %s\n" "$ext" "${prg_for[$ext]:-PROGRAM_UNDEFINED}"
done <<'EOF2'
/some/text.txt
/spaced dir/excel.xls
/spacedname/e mail.pst
/undefinedext/word.docx
/multidot/file.tar.gz
/no/extension
EOF2
非常感谢您的快速帮助。
eval
可能非常危险。。。无论如何,${!name}
要干净得多。@jm666不错,我不知道用这种方法来做!对于一个简单的回音,您是对的,它是使用${!name}
必须完成的。在这种情况下,Eval是一种过度的杀伤力。
declare -A prg_for=(
[txt]="Notepad"
[doc]="Microsoft Word"
[xls]="Microsoft Excel"
[pst]="Microsoft Outlook"
[gz]="gzip"
[tar.gz]="tar"
)
while read -r file
do
base=$(basename "$file")
[[ $base =~ ^([^.]*)\.(.*)$ ]] && ext=${BASH_REMATCH[2]} || ext="NOTHING"
printf "extension is: %10s program is: %s\n" "$ext" "${prg_for[$ext]:-PROGRAM_UNDEFINED}"
done <<'EOF2'
/some/text.txt
/spaced dir/excel.xls
/spacedname/e mail.pst
/undefinedext/word.docx
/multidot/file.tar.gz
/no/extension
EOF2
extension is: txt program is: Notepad
extension is: xls program is: Microsoft Excel
extension is: pst program is: Microsoft Outlook
extension is: docx program is: PROGRAM_UNDEFINED
extension is: tar.gz program is: tar
extension is: NOTHING program is: PROGRAM_UNDEFINED