比较 2 个文件中的字符串并将数据附加到 shell 脚本中

Comparing string in 2 files and appending the data in shell script

我有 2 个文件 1.txt 和 2.txt

1.txt 包含以下详细信息

user = 10
user2 = 20
user3 = 30

2.txt 包含以下详细信息

user = 25MB
user2 = 30MB

我需要比较这两个文件,如果文件中的字符串匹配,它应该附加第一个文件中的数据,如果不匹配,它应该在 shell 脚本

中附加 0

期望的输出

user = 10 25MB
user2 = 20 30MB
user3 = 30 0MB

我正在使用命令:

awk 'FNR==NR{a[];next}!( in a)' 1.txt 2.txt

但未获得所需的输出。我是 shell 脚本编写的新手,正在寻找完整的实施帮助。

你能帮我解决语法和实现问题吗?

你可以使用这样的东西:

$ awk 'NR == FNR { a[] = ; next } 
       { printf "%s = %s %s\n", , , ( in a ? a[] : "0MB") }' 2.txt 1.txt
user = 10 25MB
user2 = 20 30MB
user3 = 30 0MB

我选择以相反的顺序读取文件,2.txt,然后 1.txt2.txt 中的键和值存储在数组 a 中。对于 1.txt 中的每一行,如果存在,则使用与键对应的数组中的值。