Bulk Replace File Content Using Shell

In Shell, the sed command can be used to batch replace file contents. Sed is a stream editor that can be used to replace, delete, insert, and perform other operations on text. Here is an example of replacing a certain string with another string in all files in a specified directory:

#!/bin/bash

# 遍历指定目录下的所有文件
for file in /path/to/directory/*; do
    # 仅处理普通文件,排除目录和链接文件
    if [ -f "$file" ]; then
        # 使用sed命令替换文件中的内容,将"old_string"替换为"new_string"
        sed -i 's/old_string/new_string/g' "$file"
    fi
done

In the examples above, replace /path/to/directory with the path of the directory you want to process, replace old_string with the string you want to replace, and replace new_string with the string you want to replace it with. The -i option is used to directly modify the file contents, if you do not need to modify the file contents, you can delete this option.

bannerAds