Joi McClain
Joi McClain

Reputation: 47

Create a Linux shell script program that sorts the numbers and words in a file?

I need to create a Linux shell script program that reads a text file (until EOF) and does the following things:

The text file that I want the program to read is as follows:

123
apple
456
boy
789

And I want the output to be as follows:

2 WORDS, 3 NUMBERS

Plus, I want the wordsfile.txt to read:

apple
boy

And the numbersfile.txt to read:

123
456
789

This is my code:

#!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

And this is the output that I'm getting:

./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

I don't understand why my code isn't working. Please help.

Upvotes: 1

Views: 129

Answers (1)

Yimin Rong
Yimin Rong

Reputation: 2027

Linux has all these neat utilities to match numbers and words and to count them. No need to reinvent the wheel.

wf=wordsfile.txt
nf=numbersfile.txt
egrep -i '^[a-z]+$' $1 > $wf
egrep '^[0-9.]+$' $1 > $nf
W=`wc -l $wf`
N=`wc -l $nf`
echo $W WORDS, $N NUMBERS

Save as a script, then run like this:

./my-script file-to-read

Upvotes: 1

Related Questions