如何在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:
- First, process
file2: TheNR==FNRcondition 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 calledchecked—this marks which words need the suffix. - Then, process
file1: For each line infile1, we loop through every word. If the word exists in ourcheckedarray, we add:Checkedto 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 jklfile2: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
相关产品推荐
相关产品推荐

