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

如何在Shell中为包含特定单词的条目添加后缀并保持原文件排序顺序?

Yes, you can absolutely do this with a simple Awk command!

Here's a concise solution that preserves the original order of words from file1 and appends :Checked to any words that appear in file2:

awk '
BEGIN { FS=":" }
NR==FNR { checked[$1] = 1; next }
{
    output = ""
    for (i=1; i<=NF; i++) {
        output = output (output ? " " : "") ($i in checked ? $i ":Checked" : $i)
    }
    print output
}
' file2 file1

How this works:

  1. First, process file2: The NR==FNR condition only runs when we're reading the first input file (file2). We split each line using a colon as the separator, then store the word before the colon in an associative array called checked—this marks which words need the suffix.
  2. Then, process file1: For each line in file1, we loop through every word. If the word exists in our checked array, we add :Checked to it; otherwise, we leave it as-is. We build the output string with spaces between words and print the final result.

Example output:

Given your input files:

  • file1: abc def ghi jkl
  • file2:
    ghi:Checked
    def:Checked
    

Running the command will output exactly what you want:

abc def:Checked ghi:Checked jkl

This method keeps file1's order intact, works with multiple lines in either file, and handles any number of checked words from file2.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 08:52:42