0

我在 bash 中编写的脚本有一点错误,我不知道我做错了什么

请注意,我使用这个脚本进行了数千次计算,这个错误只发生了几次(比如 20 次左右),但它仍然发生了

脚本的作用是:基本上,它输入一个网页,该网页是我从具有实用程序 w3m 的站点获得的,它计算其中出现的所有单词......在它从最常见的单词到最常见的单词排序之后只发生一次

这是代码:

#!/bin/bash
#   counts the numbers of words from specific sites                       #
#   writes in a file the occurrences ordered from the most common         #

touch check         # file used to analyze the occurrences
touch distribution      # final file ordered

page=$1             # the web page that needs to be analyzed
occurrences=$2          # temporary file for the occurrences
dictionary=$3                       # dictionary used for another purpose (ignore this)

# write the words one by column
cat $page | tr -c [:alnum:] "\n" | sed '/^$/d' > check

# lopp to analyze the words
cat check | while read words
do
    word=${words}
    strlen=${#word}
    # ignores blacklisted words or small ones
    if ! grep -Fxq $word .blacklist && [ $strlen -gt 2 ]
    then
        # if the word isn't in the file
        if [ `egrep -c -i "^$word: " $occurrences` -eq 0 ]
        then
            echo "$word: 1" | cat >> $occurrences
        # else if it is already in the file, it calculates the occurrences
        else
            old=`awk -v words=$word -F": " '$1==words { print $2 }' $occurrences`
                    ### HERE IS THE ERROR, EITHER THE LET OR THE SED ###
            let "new=old+1"
            sed -i "s/^$word: $old$/$word: $new/g" $occurrences
        fi
    fi
done

# orders the words
awk -F": " '{print $2" "$1}' $occurrences | sort -rn | awk -F" " '{print $2": "$1}' > distribution

# ignore this, not important
grep -w "1" distribution | awk -F ":" '{print $1}' > temp_dictionary

for line in `cat temp_dictionary`
do
    if ! grep -Fxq $line $dictionary
    then
        echo $line >> $dictionary
    fi
done

rm check
rm temp_dictionary

这是错误:(我正在翻译它,所以英文可能会有所不同)

./wordOccurrences line:30 let:x // where x is a number, usually 9 or 10 (but also 11, 13, etc)
1: syntax error in the espression (the error token is 1)
sed: expression -e #1, character y: command 's' not terminated // where y is another number (this one is also usually 9 or 10) with y being different from x

编辑:与 kev 交谈看起来像是换行问题

我在 let 和 sed 之间添加了一个 echo 来打印 sed,它完美地工作了 5 到 10 分钟,直到出现错误。通常没有错误的 sed 看起来像这样:

s/^CONSULENTI:6 美元/CONSULENTI:7/g

但是当我收到错误时,它是这样的:

s/^00145: 1 1$/00145: 4/g

如何解决这个问题?

4

2 回答 2

2

如果你在 $old 中得到一个新行,这意味着 awk 打印了两行,所以在 $occurences 中有一个重复。

该脚本计算单词似乎很复杂,并且效率不高,因为它会循环启动许多进程和进程文件;也许你可以做类似的事情

sort | uniq -c
于 2012-08-05T13:35:50.693 回答
1

您还应该考虑到您的不区分大小写在整个程序中并不一致。我创建了一个仅包含“foooo”的页面并运行程序,然后创建了一个包含“Foooo”的页面并再次运行程序。'old=`awk...' 行将 'old' 设置为空字符串,因为 awk 区分大小写。这会导致事件文件不被更新。随后的 sed 和可能的一些 grep 也区分大小写。

这可能不是唯一的错误,因为它没有解释您看到的错误消息,但这表明您的脚本将错误地处理具有不同大小写的相同单词。

以下将分隔单词,将它们小写,然后删除小于三个字符的单词:

tr -cs '[:alnum:]' '\n' <foo | tr '[:upper:]' '[:lower:]' | egrep -v '^.{0,2}$'

在脚本的前面使用它意味着脚本的其余部分不必区分大小写即可正确。

于 2012-08-05T14:19:34.807 回答