假设文件名作为命令行参数给出。编写shell脚本以计算行,字符和单词

时间:2019-03-23 13:22:22

标签: bash shell unix

我尝试解决该问题,但无法解决最后一部分,即“假定文件名是命令行参数”

编写一个shell脚本,该脚本显示文件中单词,字符,行的总数。假定文件名作为命令行参数给出。

echo
c=$( wc -c < test.txt)
echo "Number of characters in test.txt is $c"
echo
w=$( wc -w < test.txt)
echo "Number of words in test.txt is $w"
echo
l=$( ec -l < test.txt)
echo "Number of lines in test.txt is $l"

我不得不通过2个测试用例,但是我只通过了一个测试用例,因为我无法解决将文件名作为命令行参数的问题。

9 个答案:

答案 0 :(得分:0)

这应该有效。编写脚本the_script.sh如下:

for F in ${*}
do
   echo
   c=$( wc -c < ${F})
   echo "Number of characters in ${F} is $c"
   echo
   w=$( wc -w < ${F} )
   echo "Number of words in ${F} is $w"
   echo
   l=$( wc -l < ${F})
   echo "Number of lines in ${F} is $l"
done

为说明起见,${*}是传入的命令行参数,并且与上述for循环一起使用时,在循环的每次迭代中,每个自变量都与$F关联。

然后在循环中,将${F}作为文件名。

要运行:

./the_script.sh text.txt test2.txt ....

正如其他人所指出的,如果文件很大,应该避免运行wc三次,因此,这是只运行一次并处理计数的一种方法:

WC=$( wc ${F} )
l=$( echo $WC | awk '{print $1}' )
w=$( echo $WC | awk '{print $2}' )
c=$( echo $WC | awk '{print $3}' )

答案 1 :(得分:0)

for D in ${*}

do

echo

c=$( wc -c < ${D})

echo "Number of Characters in ${D} is $c"

echo

w=$( wc -w < ${D} )

echo "Number of Words in ${D} is $w"

echo

l=$( wc -l < ${D})

echo "Number of lines in ${D} is $l"

done

答案 2 :(得分:0)

这将起作用

#!/bin/bash
echo "Number of characters in $1 `wc -m < $1`"
echo "Number of words in $1 `wc -w < $1`"
echo "Number of lines in $1 `wc -l < $1`"
  1. $ 1 :第一个参数(文件名)
  2. `` (反引号):用于执行命令
  3. 选项: -m:计数字符 -w:字数 -l:计数行数

答案 3 :(得分:0)

**您还可以使用此简单格式**

for F in test.txt
   do 
        echo
        c=$( wc -c < test.txt )
        echo "number in test.txt is $c"
    done

答案 4 :(得分:0)

 echo "Number of characters in $1 is $(wc -m < $1)"
 echo "Number of words in $1 is $(wc -w < $1)"
 echo "Number of lines in $1 is $(wc -l < $1)"

打印时需要用$ 1替换test.txt。 这将清除两个测试用例。

答案 5 :(得分:0)

使用这个简单的解决方案:

wc -c ${*} | awk '{print "Number of characters in " $2 " is " $1}'
wc -w ${*} | awk '{print "Number of words in " $2 " is " $1}' 
wc -l ${*} | awk '{print "Number of lines in "$2 " is " $1}'

答案 6 :(得分:0)

基本上,它在问题中给出了文件名将被传递一个命令行参数。所以基本上你可以通过使用该命令行参数作为变量来打印文件名(它不是所有测试用例的 test.txt )。 这是我在 Tekstac 平台中被接受的代码-

words=`cat $1 | wc -w`
char=`cat $1 | wc -c`
lines=`cat $1 | wc -l`
echo "Number of characters in $1 is $char"
echo "Number of words in $1 is $words"
echo "Number of lines in $1 is $lines"

答案 7 :(得分:-2)

passed=$1  
echo  
echo -n "Number of characters in $passed is "  
wc -c < $passed  
echo   
echo -n "Number of words in $passed is "  
wc -w < $passed  
echo  
echo -n "Number of letters in $passed is "  
wc -l < $passed  

答案 8 :(得分:-2)

尝试一下,效果很好。所有测试已清除

for F in $*

do

  echo

  c=$( wc -c < ${F} )

  echo "Number in characters in ${F} is $c"

  echo

  w=$( wc -w < ${F} )

  echo "Number in words in ${F} is $w"

  echo

  l=$( wc -l < ${F} )

   echo "Number in lines in ${F} is $l"

done