Alternatively string file read and write

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/huatian5/article/details/102770668

Some time ago wrote a script py, replacing strings in all files in a directory, but the problem occurs, if you replace a long string will be left with a short string of the last occurrence of some of the original file, the original file contents are not cleared , but in the form of replacement cover, the next check has truncate(size)a function to start from the first byte truncated size size (default cut off all), it will be solved.

#!/usr/bin/env python3

import os
import sys
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("file_directory", help="the directory contain files you want replace", default="")
    parser.add_argument("source_str", help="the source string you want replace", default="")
    parser.add_argument("destination_str", help="the destination string you want replace to", default="")
    args = parser.parse_args()
    file_dir = args.file_directory
    
    files = os.listdir(file_dir)
    for per_file in files:
        file_path = file_dir + "/" + per_file
        f = open(file_path, 'r+')
        s = f.read()
        f.seek(0, 0)
        f.truncate()
        f.write(s.replace(args.source_str, args.destination_str))
        f.close()

Then might as linux sed command of convenience:

grep -rl "Source string" . | xargs -n1 sed -i "s/Source string/Destination string/g"

Read-write mode are the following:

Access mode significance
r read
w Covering write, file does not exist will be created.
a Additional write, the file does not exist will be created.
r+ Read + Write.
w+ Read + write, the file does not exist will be created.
a+ + Read additional writing, the file does not exist will be created.

More "b", is used to represent the binary read and write

sed command

替换:s
全局:g
全局替换:替换文件中所有包含 source 为 target :
sed -i 's/source/target/g' file.txt

删除文件中包含 source 的行:
sed -i '/source/d' file.txt

删除多文件直接目录就行 ./*

Guess you like

Origin blog.csdn.net/huatian5/article/details/102770668