gpt4 book ai didi

shell - 用另一个文件中指定的值替换字段

转载 作者:行者123 更新时间:2023-12-01 08:00:46 25 4
gpt4 key购买 nike

我有一个文件,其中包含单词之间的映射。我必须引用该文件并将这些词替换为某些文件中的映射词。例如,下面的文件具有映射的单词表

1.12.2.4               1
1.12.2.7 12
1.12.2.2 5
1.12.2.4 4
1.12.2.6 67
1.12.2.12 5

我会有很多包含这些关键词的文件(1.12.2.*)。我想搜索这些关键词并将这些词替换为从此文件中获取的相应映射。如何在 shell 中执行此操作。假设一个文件包含以下几行说

The Id of the customer is 1.12.2.12. He is from Grg. 
The Name of the machine is ASB
The id is 1.12.2.4. He is from Psg.

执行脚本后,数字“1.12.2.12”和“1.12.2.4”应替换为 5 和 4(引用主文件)。谁能帮我吗?

最佳答案

使用 GNU awk 的一种方式:

awk 'FNR==NR { array[$1]=$2; next } { for (i in array) gsub(i, array[i]) }1' master.txt file.txt

结果:
The Id of the customer is 5. He is from Grg.
The Name of the machine is ASB
The id is 4. He is from Psg.

将输出保存到文件:
awk 'FNR==NR { array[$1]=$2; next } { for (i in array) gsub(i, array[i]) }1' master.txt file.txt > name_of_your_output_file.txt

说明:
FNR==NR { ... }   # FNR is the current record number, NR is the record number
# so FNR==NR simply means: "while we process the first file listed
# in this case it's "master.txt"
array[$1]=$2 # add column 1 to an array with a value of column 2
next # go onto the next record

{ # this could be written as: FNR!=NR
# so this means "while we process the second file listed..."
for (i in array) # means "for every element/key in the array..."
gsub(i, array[i]) # perform a global substitution on each line replacing the key
# with it's value if found
}1 # this is shorthand for 'print'

添加词边界使匹配更加严格:
awk 'FNR==NR { array[$1]=$2; next } { for (i in array) gsub("\\<"i"\\>", array[i]) }1' master.txt file.txt

关于shell - 用另一个文件中指定的值替换字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12400217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com