需要帮助来替换 linux 中与键名匹配的行

需要帮助来替换 linux 中与键名匹配的行

输入文件(有 2 行,有 2 个键值对):

key1 = "x"
key2 = ['a', 'b', 'c']

使用此输入文件,我需要替换另一个文件上的键值对。

File1(有 2 行,有 2 个键值对):

key1 = "y"
key2 = ['p' , 'q', 'r']

请告诉我 shell 脚本中是否有任何简单的方法来完成此任务。

答案1

不完全确定您要存档的内容。假设您要修补file.txt包含文本和键值对的文件,如下所示

key1
key2
text
key1 = "original"
key2 = ['o' , 'r', 'i', 'g']
text

patchfile.txt包含要替换的值的键值对,如下所示

key1 = "patched"
key2 = ['p', 'a', 't', 'c', 'h']

不覆盖文本key1/key2不是键值对以获得file.txt这样的结果

key1
key2
text
key1 = "patched"
key2 = ['p', 'a', 't', 'c', 'h']
text

通过发出这样的命令

patchmystuff.sh file.txt patchfile.txt

的内容patchmystuff.sh可能如下所示:

#!/usr/bin/env bash

original_file=$1
patch_file=$2

# loop from here:
# https://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash
while IFS="" read -r line || [ -n "$line" ]
do
    printf 'patching %s\n' "$line"
    # (?<==) is the lookbehind for = to keep it
    # otherwise it will match key1/key2 in regular text
    search_string=$(echo "$line" | perl -ne 's/(?<==).*//g; print;')
    printf 'search string: "%s"\n' "$search_string"
    sed -i -e "s/$search_string.*/$line/g" "$original_file"
done < "$patch_file"

相关内容