2016-11-28 158 views
0

我正在尝试编写脚本以允许用户输入文件名并显示文件中的行数,单词数,字符数或全部三个数,具体取决于是否用户输入'l'(行),'w'(字),'c'(字符)或'a'(全部)。如何将用户定义的变量与字符串文字进行比较

这是我到目前为止有:

#!/bin/sh                               

# Prompt for filename                            
read -p 'Enter the file name: ' filename 

# Prompt which of lines, words, or chars to display                    
read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
while [ $display -ne "l" -o $display -ne "w" -o $display -ne "c" -o $display -ne "a" ] 
do 
    echo "Invalid option" 
    read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
done 

# Display to stdout number of lines, words, or chars                    
set `wc $filename` 
if [ $display -eq "l" ] 
then 
    echo "File '$4' contains $1 lines." 
elif [ $display -eq "w" ] 
then 
    echo "File '$4' contains $2 words." 
elif [ $display -eq "c" ] 
then 
    echo "File '$4' contains $3 characters." 
else 
    echo "File '$4' contains $1 lines, $2 words, and $3 characters." 
fi 

如果我运行该脚本,并提供了一个名为trial.txt文件,并选择选项w,我得到的输出:

./icount: 11: [: Illegal number: w 
./icount: 19: [: Illegal number: w 
./icount: 22: [: Illegal number: w 
./icount: 25: [: Illegal number: w 
File 'trial.txt' contains 3 lines, 19 words, and 154 characters. 

有人可以帮助我解释这个错误?

回答

0

我想通了。 -eq-ne是整数比较运算符。比较字符串时必须使用=!=

+0

真正使用AND conditions。但即使有了这种修正,如果用户给出一个空输入,输入'hi there',或者在大多数情况下输入'*',脚本就会失败。对于奖励积分,请使用引号或(通常在ksh/bash/etc中更好)''['也可以解决这些问题。 –

0

你也应该在while循环

#!/bin/sh                               

# Prompt for filename                            
read -p 'Enter the file name: ' filename 

# Prompt which of lines, words, or chars to display                    
read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
while [ "$display" != "l" -a "$display" != "w" -a "$display" != "c" -a "$display" != "a" ] 
do 
    echo "Invalid option" 
    read -p 'Count lines, words, characters, or all three (l, w, c, a)? ' display 
done 

# Display to stdout number of lines, words, or chars                    

set `wc $filename` 
if [ $display == "l" ] 
then 
    echo "File '$4' contains $1 lines." 
elif [ $display == "w" ] 
then 
    echo "File '$4' contains $2 words." 
elif [ $display == "c" ] 
then 
    echo "File '$4' contains $3 characters." 
else 
    echo "File '$4' contains $1 lines, $2 words, and $3 characters." 
fi 
相关问题