-3

Hello guys I'm literally stuck in this damn - before exam exercise.

Exercise: Write a scrypt wich gonna handle a name of a file ( as a first Argument ) and count amount of those numbers and letters in this file. Scrypt should also sum all of those numbers.

1 2 3 4 5
9 2 3 1 2 a l a i o l a 
9 2 ala ma kota 102

How it should looks like:

 File ....... have 15 numbers and 16 letters.
 Sum of all of those numbers is 145.  

Mine idea how should I deal with this exercise(step by step)

  1. catch the name of a file ( as an argument )
  2. Parse the whole data into one line ( for easy sort )
  3. Numberic sort for whole data ( to get result like this 1 2 3 4 5 6 (...)102 a a a a a a a i k m (...)
  4. Set up first numbers as Arguments ($1-$13) for easy sum & count+ set up letters as Arguments for easy count
  5. Pop everything into console
  6. Enjoy mine life and play overwatch ( joke, getting back 2 learning Linux {lovely before exams stuffs } )

    Stuff on wich I'm stuck.

    Step 2. After parsing those data im getting ( tried literally everything wich I could find ):

    1 2 3 4 5 9 2 3 1 2 a l a i o l a 9 2 ala ma kota 102
    

Truelly don't know how to merge those 3 lines into 1 line, whenever im trying 2 sort i'm getting back into the beginning.

echo `cat kolos3 | xargs | sort -n `  

Would be great if any of you guys would be able to help me with this exercise.

  • 1
    I would do the opposite: tr ' ' \\n to have them one per line. Then it's easier to count - with a tool like awk - how many lines with letters (and sum their length) and how many with digits (and sum their values). – don_crissti Jun 03 '16 at 01:04
  • ... or even just awk with its record separator set to any sequence of one or more whitespace characters [ \t\n]+ – steeldriver Jun 03 '16 at 01:29
  • 1
    Either you did not reproduce precisely your assignment or the assignment is incorrect: the sample output contains the number of digits in the input file and the sum of numbers. Numbers and digits are not the same thing. – Serge Jun 03 '16 at 01:38

1 Answers1

1

grep -o will do most of the work here, whether you join the inputs onto the same line or not.

-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

To count the letters:

grep -o "[[:alpha:]]" "$file" | wc -l

To count the digits:

grep -o "[[:digit:]]" "$file" | wc -l

But if you instead want the numbers:

grep -o "[[:digit:]]\+" "$file" | wc -l

To sum the numbers, you could use any of the solutions on How do I create a bash script that sums any number of command line arguments?

I would pass that problem to bc:

(grep -o "[[:digit:]]\+" "$file" | tr '\n' + ;echo 0)|bc
JigglyNaga
  • 7,886