查找并将一个文件中包含的行字符串替换为shell脚本中的第二个文件

时间:2021-11-05 15:29:52

I'm trying to find a solution to the following problem:

我正在尝试找到以下问题的解决方案:

I have two files: i.e. file1 and file2. In file1 there some lines with some key words and I want to find these lines in file2 by using the key words. Once find the key words in file2 I would like to update this line with the content of the same line in file1. This operation should be done for every line contained in file1.

我有两个文件:即file1和file2。在file1中有一些带有一些关键词的行,我想通过使用关键词在file2中找到这些行。一旦找到file2中的关键字,我想用file1中同一行的内容更新这一行。应对file1中包含的每一行执行此操作。

Just an example of what I have in mind, but I don't know exactly how to transform in shell script command.

只是我想到的一个例子,但我不确切知道如何在shell脚本命令中进行转换。

file1:

key1=new_value1
key2=new_value2
key3=new_value3
etc....

file2:

key1=value1
key2=value2
key3=value3
key4=value4
key5=value5
key6=value6
etc....


Result:

key1=new_value1
key2=new_value2
key3=new_value3
key4=value4
key5=value5
key6=value6
etc....

I don't know how can I use 'sed' or something else in shell script to accomplish this task. Any help is welcomed.

我不知道如何在shell脚本中使用'sed'或其他东西来完成这项任务。欢迎任何帮助。

Thank you

谢谢

1 个解决方案

#1


1  

awk would be my first choice

awk将是我的第一选择

awk -F= -v OFS== '
    NR==FNR {new[$1]=$2; next} 
    $1 in new {$2=new[$1]} 
    {print}
' file1 file2

#1


1  

awk would be my first choice

awk将是我的第一选择

awk -F= -v OFS== '
    NR==FNR {new[$1]=$2; next} 
    $1 in new {$2=new[$1]} 
    {print}
' file1 file2