Sed is a good file processing tool, itself is a pipeline command, mainly in the behavior of the unit processing, you can replace the data rows, delete, add, select and other specific work. Now with Python simple implementation of the main sed command, the old_text replaced with New_text, while the original file backup, the original file was modified.
The contents of sed.py are as follows:
1 ImportSYS2 ImportOS3 ImportShutil4 5 ifLen (SYS.ARGV) < 4:6Sys.exit ("usage:sed.py old_text new_text file_name")7 8 #assuming that the program's parameters are correct9 #assigning values to parametersTenProgran_ame, Old_text, new_text, arg_file_name =SYS.ARGV One Print(Progran_ame, Old_text, New_text, Arg_file_name) A - if notos.path.exists (arg_file_name): -Sys.exit ("file%s does not exist"%arg_file_name) the - - #determines whether the input parameter is an absolute path, or an absolute path if it is a relative path - ifOs.path.isabs (arg_file_name): +Src_file =Arg_file_name - Else: +Src_file =Os.path.realpath (arg_file_name) A at #Rename the original file to get the backup file name -Src_path_name =os.path.dirname (src_file) -Src_file_name =os.path.basename (src_file) -Bak_file_name = Os.path.splitext (src_file_name) [0]+'_bak'+os.path.splitext (src_file_name) [1] -Back_file = src_path_name+os.sep+Bak_file_name - in #Backup Files - shutil.copy (Src_file, Back_file) to +Out_file = open (Src_file,'W', encoding='Utf-8') - #iterate through each line of the file, with the substitution operation theWith open (Back_file, encoding='Utf-8') as F: * forLineinchF: $ Out_file.writelines (Line.replace (Old_text, new_text))Panax Notoginseng -Out_file.close ()
Test
Test.txt file contents are as follows
BJ Hello I am a little fool welcome you ... bj
Python sed.py BJ Beijing Test.txt
Replace "BJ" in Test.txt with "Beijing"
After execution, generate the Test_bak.txt file with the same content as the test.txt. The content in Test.txt becomes
BEIJING hello I am a little fool welcome you ... Beijing
Using Python3 to realize the SED function of Linux