简体   繁体   English

根据行号合并两个文件,其中第一个文件中的行优先

[英]Merge two files based on line numbers where lines from the first file take priority

I'm on Unix and I need to replace lines in a file. 我在Unix上,需要替换文件中的行。

I have this file 我有这个档案

1:F
3:M
5:Z
7:Q

And I need to replace lines before the : to this file 我需要在此文件的:之前替换行

1:A
2:B
3:C
4:D
5:E
6:F
7:G
8:H
9:I
10:J
11:K
12:L

The final result should look like this 最终结果应如下所示

1:F
2:B
3:M
4:D
5:Z
6:F
7:Q
8:H
9:I
10:J
11:K
12:L

How can I do that? 我怎样才能做到这一点?

You can use this awk command: 您可以使用以下awk命令:

awk -F: 'FNR==NR{a[$1]=$2; next} $1 in a{$0 = $1 FS a[$1]} 1' file1 file2

1:F
2:B
3:M
4:D
5:Z
6:F
7:Q
8:H
9:I
10:J
11:K
12:L

Do read about awk here: Effective AWK Programming 在这里阅读有关awk有效的AWK编程

If the lines in the short file are in the order in which they have to go into the longer file, you can use join and cut : 如果短文件中的行按它们进入长文件的顺序排列,则可以使用joincut

$ join --nocheck-order -a 2 -t ':' file1 file2 | cut -d ':' -f 1,2
1:F
2:B
3:M
4:D
5:Z
6:F
7:Q
8:H
9:I
10:J
11:K
12:L

--nocheck-order makes join ignore that the input files aren't lexically, sorted; --nocheck-order使得join忽略输入文件都没有词法,排序; -a 2 prints also non-matching lines from the longer file ( file2 ); -a 2还从较长的文件( file2 )中打印不匹配的行; -t ':' sets the delimiter to a colon. -t ':'将定界符设置为冒号。 The output of just the join command is 只是join命令的输出是

1:F:A
2:B
3:M:C
4:D
5:Z:E
6:F
7:Q:G
8:H
9:I
10:J
11:K
12:L

and with cut , we get the first two colon separated columns of this. 并通过cut ,得到前两个冒号分隔的列。

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

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