简体   繁体   English

Bash-查找并替换目录中文件中的一行

[英]Bash - Find and replace a line in a file in number of directories

I have a file structure where I have 700 directories. 我有一个文件结构,其中有700个目录。 All the directories have a file named config.xml . 所有目录都有一个名为config.xml的文件。 I have prefixed 25 directories with 1111- name. 我为25个目录添加了1111-名称。 Now, I want to replace a block of code in config.xml files from all those 25 directories. 现在,我想替换所有这25个目录中的config.xml文件中的代码块。 I want to have a loop ( for or while ) for that. 我想要一个循环( forwhile )。

您可以使用find搜索文件, grep目录并使用sed替换字符串。

find . -iname 'config.xml' | grep '1111' | sed -i 's/STRINGTOREPLACE/NEWSTRING/'

尝试这个:

find . -name "1111-*" -type d -exec cd {} \; -exec /absolute.path/to/shell_script_modifying_config.xml \;

I would use a recursive function: 我将使用递归函数:

folder_recursive() {
    for i in "$1"/*;do
        if [ -d "$i" ];then
            folder_recursive "$i"
        elif [ -f "$i" ]; then
            lastFolder = ${$1##*/}
            if [[ $lastFolder == *"1111-"* ]]; then
                if [[ $i == *"config.xml" ]]; then
                    #Replace block of code
                    file_path=$i
                    original=$(<file_path) # Read from file
                    to_replace="aaaabbbb"
                    replacer="xxxxyyyy"
                    result=${original/$to_replace/$replacer} #This will replace the first instance of to_replace
                    # If you want to replace all instances use:
                    # ${original//$to_replace/$replacer}
                    echo $result > $i #Overwrite file
                fi
            fi
        fi
    done
}

path= "root/of/folder/structure"
folder_recursive $path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM