问题描述
可能重复:结果
How基于匹配关键字段,我可以用从另一个文件行的文本文件行?
我要合并下列文件,我想FileB.txt的内容覆盖FileA.txt在有着共同的线,但我不希望与FileB.txt完全取代FileA.txt。
I want to merge the following files and I want the contents of FileB.txt to overwrite FileA.txt where there are common lines, but I don't want to completely replace FileA.txt with FileB.txt.
例如:
文件:
# cat FileA.txt
interface.1.type = ethernet
interface.1 = A
interface.1.ip = 192.168.1.1
interface.1.netmask = 255.255.255.0
interface.1.dhcp = false
文件B:
# cat FileB.txt
interface.1 = B
interface.1.ip = 192.168.1.1
interface.1.netmask =
interface.1.dhcp = true
interface.1.dhcp.range = 192.168.1.1,192.168.1.15
interface.1.extraline =
在这种情况下
合并的结果应该是:
In this caseThe merge result should be:
# cat FileA.txt
interface.1.type = ethernet
interface.1 = B
interface.1.ip = 192.168.1.1
interface.1.netmask =
interface.1.dhcp = true
interface.1.dhcp.range = 192.168.1.1,192.168.1.15
interface.1.extraline =
在每行前的=所以,任何事情,应检查并FileA.txt和FileB.txt之间的匹配。如果有任何后'='上FileB.txt从FileA.txt不同则无论是在FileB.txt应写入FileA.txt。
So anything before the '=' on each line should be checked and matched between FileA.txt and FileB.txt. If any after the '=' on FileB.txt differs from FileA.txt then whatever is in FileB.txt should be written to FileA.txt.
推荐答案
试试这个排序
命令:
sort -t= -k1,1 -us FileB.txt FileA.txt
-t =
:分割线成田的'=',所以要排序上的按键
-t=
: split the lines into fields on the '=', so you are sorting on the keys
-k1,1
:排序的第一个字段。这是重要的,因为复制(见下文)取决于
只在指定的排序字段。
-k1,1
: sort on the first field. This is important, as duplication (see below) dependsonly on the specified sort field.
-u
:消除重复。如果两行具有相同的密钥,只有第一保持
-u
: eliminate duplicates. If two lines have the same key, only the first is kept.
-s
:稳定排序。如果根据自己的排序字段,行两行是相同的
第一次出现在输入保持第一输出。
-s
: stable sort. If two lines are identical based on their sort field, the line thatis seen first in the input remains first in the output.
通过将 FileB.txt
输入列表中第一个文件,可以确保从线路 FileB.txt
选择在从 FileA.txt
行,如果他们共享同一个密钥。
By putting FileB.txt
in the list of input files first, you ensure that the line fromFileB.txt
is chosen over the line from FileA.txt
if they share the same key.
这篇关于我如何合并FileA.txt和FileB.txt给FileB.txt覆盖电源使用bash脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!