在unix shell脚本中不使用“wc”命令计算文本文件中的单词数

在unix shell脚本中不使用“wc”命令计算文本文件中的单词数,shell,Shell,在这里,我找不到文本文件中的字数。我需要做哪些可能的更改? tty在这个程序中有什么用途 echo "Enter File name:" read filename terminal=`tty` exec < $filename num_line=0 num_words=0 while read line do num_lines=`expr $num_lines + 1` num_words=`expr $num_words + 1`

在这里,我找不到文本文件中的字数。我需要做哪些可能的更改? tty在这个程序中有什么用途

echo "Enter File name:"  
read filename  
terminal=`tty`  
exec < $filename  
num_line=0  
num_words=0
while read line  
do  
    num_lines=`expr $num_lines + 1`  
    num_words=`expr $num_words + 1`  
done    
tty命令打印连接到标准输出的终端的名称。在您的程序上下文中,它实际上没有什么意义,您最好删除该行并运行它


关于字数计算,您需要解析每一行,并使用空格作为分隔符来查找它。目前,程序只查找行数$num_行,并对$num_字使用相同的计算。

有一种简单的方法,使用数组读取文件中的字数:

#!/bin/bash

[ -n "$1" ] || { 
    printf printf "error: insufficient input. Usage: %s\n" "${0//\//}"
    exit 1
}

fn="$1"

[ -r "$fn" ] || {
    printf "error: file not found: '%s'\n" "$fn"
    exit 1
}

declare -i cnt=0

while read -r line || [ -n "$line" ]; do        # read line from file
    tmp=( $line )                               # create tmp array of words
    cnt=$((cnt + ${#tmp[@]}))                   # add no. of words to count
done <"$fn"

printf "\n %s words in %s\n\n" "$cnt" "$fn"     # show results

exit 0
输出:

wc-w确认:

tty


terminal=tty的使用将当前交互shell的终端设备分配给terminal变量。这是一种确定您连接到哪个tty设备的方法,例如/dev/pts/4

对于每一行,您将增加一个字数。您需要找到该行中的字数并将其添加到num_words中。好的。。因此,对于每一行,我需要分配set$num_lines命令,然后尝试增加字数。这就是你想说的吗?我没说要给num_行赋值。。每行都有几个字。目前,您正在计算每行一个单词,然后直接进入下一行。你需要把单词数成一行。就是这样。我试着设置$num\u行,然后添加语句num\u words=expr$num\u words+$。通过添加$,而不是1,可以获得正确的字数。我可以使用set$num_行,然后增加字数吗?
$ cat dat/wordfile.txt

Here I could not find the number of words in the text file. What 
would be the possible changes do I need to make? What is the use 
of tty in this program?
$bash wcount.sh dat/wordfile.txt

 33 words in dat/wordfile.txt
$ wc -w dat/wordfile.txt
33 dat/wordfile.txt