-5

This question was asked by the interviewer today. Suppose there is a file named "Myfile.txt" and it's contains are as below:(not necessarily in one line)

1 3 4
4 1 5
1 9 8
3 2 1
6 0 0
3 4 5
7 8 9

I want to write a script that will tell me which number has how many occurrences in that file. You can see it has numbers from 0 to 9. As you can see "1" is repeated 4 times in this file, the output should tell me that "The number 1 is used 4 times in this file."

  • Should this be in python or bash or does not matter? – coffeMug Jun 11 '16 at 17:39
  • 1
    Bash Script only – Debasish Jun 11 '16 at 17:48
  • 2
    My answer to this interview question would be "Why?" – alexis Jun 11 '16 at 19:17
3

If the file can have multiple numbers per line, it is simpler to change that into one per line first and then count. For example:

$ tr ' ' '\n' < file| sort | uniq -c
  2 0
  4 1
  1 2
  3 3
  3 4
  2 5
  1 6
  1 7
  2 8
  2 9

If you really need verbose output, you could further parse that to:

$ tr ' ' '\n' < file| sort | uniq -c | while read cnt num; do printf 'The number %s appears %s times in the file\n' "$num" "$cnt"; done
The number 0 appears 2 times in the file
The number 1 appears 4 times in the file
The number 2 appears 1 times in the file
The number 3 appears 3 times in the file
The number 4 appears 3 times in the file
The number 5 appears 2 times in the file
The number 6 appears 1 times in the file
The number 7 appears 1 times in the file
The number 8 appears 2 times in the file
The number 9 appears 2 times in the file

Or:

$ tr ' ' '\n' < file| sort | uniq -c | awk '{print "The number "$2" appears "$1" times in the file"}'
The number 0 appears 2 times in the file
The number 1 appears 4 times in the file
The number 2 appears 1 times in the file
The number 3 appears 3 times in the file
The number 4 appears 3 times in the file
The number 5 appears 2 times in the file
The number 6 appears 1 times in the file
The number 7 appears 1 times in the file
The number 8 appears 2 times in the file
The number 9 appears 2 times in the file
0
$ awk -v RS='[[:space:]]+' \
     '{ n[$1]++ };

      END {
        for (i in n) {
          print i":",n[i]
        }
      }' debasish.txt 

(this is a one-liner, with added newlines and indenting for readability)

Set the record separator (RS) to 1-or-more of any kind of whitespace (spaces, tabs, newlines, etc), and then keep count of each number seen in the array n. Print the total for each element of n at the end of the input.

Output:

0: 2
1: 4
2: 1
3: 3
4: 3
5: 2
6: 1
7: 1
8: 2
9: 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.