创建一个Linux shell脚本程序,对文件中的数字和单词进行排序?

时间:2018-05-12 03:52:56

标签: linux bash shell unix

我需要创建一个Linux shell脚本程序来读取文本文件(直到EOF)并执行以下操作:

  • 确定每一行是包含单词还是数字
  • 记录发现了多少单词
  • 将找到的每个单词附加到文本文件中(例如wordsfile.txt)
  • 将找到的每个号码附加到文本文件中(例如numbersfile.txt)
  • 返回以下所有信息

我希望程序读取的文本文件如下:

123
apple
456
boy
789

我希望输出如下:

2 WORDS, 3 NUMBERS

另外,我希望wordsfile.txt读取:

apple
boy

并且要读取numbersfile.txt:

123
456
789

这是我的代码:

#!bin/bash
wordcount=0
numbercount=0
while read line; dp
  for word in $line; do
    $wordcount = $wordcount + 1
    echo word >> /words/wordsfile.txt
  done
  for number in $line; do
    $numbercount = $numbercount + 1
    echo number >> /numbers/numbersfile.txt
  done
  echo $wordcount " WORDS, " $numberscount " NUMBERS"
done

这是我得到的输出:

./assignment6.sh < assignment6file.txt
./assignment6.sh: line 5: 0: command not found
./assignment6.sh: line 6: /words/wordfile.txt: No such file or directory
./assignment6.sh: line 9: 0: command not found
./assignment6.sh: line 10: /numbers/numbersfile.txt: No such file or directory
0  words,  0  numbers
./assignment6.sh: line 5: 0: command not found
./assignment6.sh: line 6: /words/wordfile.txt: No such file or directory
./assignment6.sh: line 9: 0: command not found
./assignment6.sh: line 10: /numbers/numbersfile.txt: No such file or directory
0  words,  0  numbers
./assignment6.sh: line 5: 0: command not found
./assignment6.sh: line 6: /words/wordfile.txt: No such file or directory
./assignment6.sh: line 9: 0: command not found
./assignment6.sh: line 10: /numbers/numbersfile.txt: No such file or directory
0  words,  0  numbers
./assignment6.sh: line 5: 0: command not found
./assignment6.sh: line 6: /words/wordfile.txt: No such file or directory
./assignment6.sh: line 9: 0: command not found
./assignment6.sh: line 10: /numbers/numbersfile.txt: No such file or directory
0  words,  0  numbers
./assignment6.sh: line 5: 0: command not found
./assignment6.sh: line 6: /words/wordfile.txt: No such file or directory
./assignment6.sh: line 9: 0: command not found
./assignment6.sh: line 10: /numbers/numbersfile.txt: No such file or directory
0  words,  0  numbers

我不明白为什么我的代码不起作用。请帮忙。

1 个答案:

答案 0 :(得分:2)

Linux拥有所有这些简洁的工具来匹配数字和单词并对它们进行计数。无需重新发明轮子。

./my-script file-to-read

另存为脚本,然后按以下方式运行:

def maker(a, b, n):
    margin_top = 2
    padding = 4
    def message(msg):
        print('\n’ * margin_top, a * n, 
            ' ‘ * padding, msg, ' ‘ * padding, b * n)
    return message

f = maker('*', '#', 5)
g = maker('', '♥’, 3)
…
f('hello')
g(‘good bye!')