Best way to simulate “group by” from bash?

前端 未结 14 1083
半阙折子戏
半阙折子戏 2020-11-29 15:03

Suppose you have a file that contains IP addresses, one address in each line:

10.0.10.1
10.0.10.1
10.0.10.3
10.0.10.2
10.0.10.1

You need a

14条回答
  •  生来不讨喜
    2020-11-29 15:47

    You probably can use the file system itself as a hash table. Pseudo-code as follows:

    for every entry in the ip address file; do
      let addr denote the ip address;
    
      if file "addr" does not exist; then
        create file "addr";
        write a number "0" in the file;
      else 
        read the number from "addr";
        increase the number by 1 and write it back;
      fi
    done
    

    In the end, all you need to do is to traverse all the files and print the file names and numbers in them. Alternatively, instead of keeping a count, you could append a space or a newline each time to the file, and in the end just look at the file size in bytes.

提交回复
热议问题