Guest User

Untitled

a guest
Apr 25th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. import os
  2. import re
  3. from os.path import walk
  4. for root, dirs, files in os.walk("/home/noa/Desktop/codes"):
  5. for name in dirs:
  6. re.search("dbname=noa user=noa", "dbname=masi user=masi")
  7. // I am trying to replace here a given match in a file
  8.  
  9. #!/usr/bin/python
  10.  
  11. import os
  12. import re
  13. import sys
  14.  
  15. # list of extensions to replace
  16. replace_extensions = []
  17. # example: uncomment next line to only replace *.c, *.h, and/or *.txt
  18. # replace_extensions = [".c", ".h", ".txt"]
  19.  
  20. def try_to_replace(fname):
  21. if replace_extensions:
  22. return fname.lower().endswith(replace_extensions)
  23. return True
  24.  
  25.  
  26. def file_replace(fname, pat, s_after):
  27. # first, see if the pattern is even in the file.
  28. with open(fname) as f:
  29. if not any(re.search(pat, line) for line in f):
  30. return # pattern does not occur in file so we are done.
  31.  
  32. # pattern is in the file, so perform replace operation.
  33. with open(fname) as f:
  34. out_fname = fname + ".tmp"
  35. out = open(out_fname, "w")
  36. for line in f:
  37. out.write(re.sub(pat, s_after, line))
  38. out.close()
  39. os.rename(out_fname, fname)
  40.  
  41.  
  42. def mass_replace(dir_name, s_before, s_after):
  43. pat = re.compile(s_before)
  44. for dirpath, dirnames, filenames in os.walk(dir_name):
  45. for fname in filenames:
  46. if try_to_replace(fname):
  47. fullname = os.path.join(dirpath, fname)
  48. file_replace(fullname, pat, s_after)
  49.  
  50. if len(sys.argv) != 4:
  51. u = "Usage: mass_replace <dir_name> <string_before> <string_after>n"
  52. sys.stderr.write(u)
  53. sys.exit(1)
  54.  
  55. mass_replace(sys.argv[1], sys.argv[2], sys.argv[3])
  56.  
  57. import os
  58.  
  59. def recursive_replace( root, pattern, replace )
  60. for dir, subdirs, names in os.walk( root ):
  61. for name in names:
  62. path = os.path.join( dir, name )
  63. text = open( path ).read()
  64. if pattern in text:
  65. open( path, 'w' ).write( text.replace( pattern, replace ) )
  66.  
  67. find /home/noa/Desktop/codes -type f -print0 |
  68. xargs -0 sed --in-place "s/dbname=noa user=noa/dbname=masi user=masi"
  69.  
  70. import os, fnmatch
  71. def findReplace(directory, find, replace, filePattern):
  72. for path, dirs, files in os.walk(os.path.abspath(directory)):
  73. for filename in fnmatch.filter(files, filePattern):
  74. filepath = os.path.join(path, filename)
  75. with open(filepath) as f:
  76. s = f.read()
  77. s = s.replace(find, replace)
  78. with open(filepath, "w") as f:
  79. f.write(s)
  80.  
  81. findReplace("some_dir", "find this", "replace with this", "*.txt")
Add Comment
Please, Sign In to add comment