You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux下如何用另一文件的指定行替换目标文件对应行

Solution Using Awk

The perfect tool for this kind of targeted replacement in Linux is awk, which excels at handling key-value mappings and text processing. Here's a straightforward command that does exactly what you need:

awk '
# First, read file2 and store replacements in an associative array
NR == FNR {
    key = $1 " " $2
    map[key] = $3
    next
}
# Then process file1, replacing values where a match exists in the map
{
    current_key = $1 " " $2
    if (current_key in map) {
        print $1, $2, map[current_key]
    } else {
        print $0
    }
}' file2 file1 > file3

How This Works:

  • Reading file2: The NR == FNR block runs only when processing the first input file (file2). For each line, we create a key from the first two fields (e.g., A1 4) and store the third field (e.g., A) in the map array.
  • Processing file1: For each line in file1, we check if the key (first two fields) exists in our map. If it does, we print the first two fields plus the replacement value from file2. If not, we print the original line as-is.

Expected Output (file3):

Assuming each triplet in your input is a separate line, file3 will look like this:

A1 1 NA
A1 2 NA
A1 3 NA
A1 4 A
A1 5 B
A1 6 T
A1 7 NA
A1 8 NA
A1 9 NA
A2 1 NA
A2 2 NA
A2 3 T
A2 4 NA

If Your Files Are Single Lines (All Triplets Space-Separated):

If your input files are actually single lines with all triplets separated by spaces (as written in your question), use this modified command to process the line in groups of three:

awk '
NR == FNR {
    key = $1 " " $2
    map[key] = $3
    next
}
{
    for (i = 1; i <= NF; i += 3) {
        current_key = $(i) " " $(i+1)
        if (current_key in map) {
            $(i+2) = map[current_key]
        }
    }
    print $0
}' file2 file1 > file3

This will output a single line with the updated triplets, matching your original input format but with the specified replacements.

内容的提问来源于stack exchange,提问作者RKG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:39:49