fork download
  1. #!/bin/bash
  2. # ideone boilerplate: run in temp dir
  3. t=$(mktemp -d -t ideone.XXXXXXXX) || exit
  4. trap 'rm -rf "$t"' ERR EXIT
  5. cd "$t"
  6.  
  7. cat <<\: >test.txt
  8. *Title Test
  9. 12125
  10. 124125
  11. asdas 1 1 1 1
  12. rthtr 1 1 1 1
  13. asdasf 1 1 1 1
  14. asfasf 1 1 1 1
  15. blabla 1 1 1 1
  16. 124124124
  17. *Title Dunno
  18. 12125
  19. 124125
  20. 12763125 1 1 1 1
  21. ijkl
  22. whatever 1 1 1 1
  23. 214142122
  24. :
  25.  
  26. cat <<\: >test.py
  27. transitions = dict()
  28. in_region = False
  29. reg_end = -1
  30. current_title = None
  31. with open("test.txt","r") as testfile:
  32. content = testfile.readlines()
  33.  
  34. for idx, line in enumerate(content):
  35. if line.startswith('*Title '):
  36. # Commit last transition before this to dict, if any
  37. if current_title:
  38. transitions[reg_end] = current_title
  39. # strip final newline
  40. current_title = line.rstrip('\n') + '2\n'
  41. elif line.strip().endswith(' 1 1 1 1'):
  42. in_region = True
  43. reg_end = idx
  44. elif in_region:
  45. in_region = False
  46. transitions[reg_end] = current_title
  47.  
  48. with open("test.txt", "w") as output:
  49. for idx, line in enumerate(content):
  50. output.write(line)
  51. if idx in transitions:
  52. output.write(transitions[idx])
  53. :
  54.  
  55. python3 test.py
  56.  
  57. cat test.txt
Success #stdin #stdout 0.01s 9240KB
stdin
Standard input is empty
stdout
*Title Test
12125
124125
asdas 1 1 1 1
rthtr 1 1 1 1
asdasf 1 1 1 1
asfasf 1 1 1 1
blabla 1 1 1 1
*Title Test2
124124124
*Title Dunno
12125
124125
12763125 1 1 1 1
ijkl
whatever 1 1 1 1
*Title Dunno2
214142122