0

I have three txt files that have this format:

File 1:

{
"username1":10,
"username2":11,
"username3":100,
}

File 2:

{
"username1":4,
"username5":15,
"username6":25,
}

File 3:

{
"username1":6,
"username2":19,
"username6":25,
}

I would like a json file (a dict object) containing the sum of the values of each username. That is, I would like:

{
"username1":20,
"username2":30,
"username3":100,
"username5":15,
"username6":50,
}

Each username could appear in each file; each username will occur a maximum of 1 time in each file. The string usernamei is an alphanumeric string of length >=1. It could be Stacy60 or evergreen or 0, etc.

That is, if username1 appears in file1, it only appears once in file1; it could appear again in file2 or file3 or both, but only once in each file.

Since these are txt files, I'm having a hard time reading them in as dict objects in Python, and thought there might be a nice grep or cat solution to this. I'm not sure how to get it right, though. I've tried:

grep -o '[[:alnum:]]":"[0-9]+" ./file_*.txt | cut -d '"' f1 | sort | uniq -c > all_usernames.json

It didn't work, and I'm not sure how to fix it.

  • 1
    Does the last entry in each object actually have a comma at the end? If so, neither input nor output is valid JSON. – Kusalananda Mar 31 at 19:23
  • Yes, each entry does have a comma at the end. – StatsSorceress Mar 31 at 20:12
  • 1
    Python has a good json package that would make short work of this. – stolenmoment Mar 31 at 20:21
  • Except each input file is not in json format; they're txt files. Does that matter? – StatsSorceress Mar 31 at 20:45
  • @StatsSorceress There can be various nice solutions through command line, but are you sure you wouldn't like a python solution ? that format is exactly python's format for dict literals and those files can be easily slurped in by a very short and simple python script – LL3 Mar 31 at 22:19

Your Answer

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

Browse other questions tagged or ask your own question.