gpt4 book ai didi

linux - 如何根据另一个文件中的相应值来划分列?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:27 24 4
gpt4 key购买 nike

我有多个文件 (66),我想将每个文件的第 3 列划分为其在 info.file 中的相应值,并将新值插入每个文件的第 4 列。我的手动代码是:

awk '{print $4=$3/NUmber from info.file}1' file 

但这需要我为每个单独的文件做几个小时。所以我想为所有文件自动化它。谢谢

file1:
chrm name value
4 a 8
3 b 4

file2:
chrm name value
3 g 6
5 s 12

info.file:
file_name average
file1 8
file2 6
file3 10

输出:

 file1:
chrm name value new_value
4 a 8 1
3 b 4 0.5

file2:
chrm name value new_value
3 g 6 1
5 s 12 2

最佳答案

没有错误处理

$ awk 'NR==FNR {a[$1]=$2; next} 
FNR==1 {out=FILENAME".new"; print $0, "new_value" > out; next}
{v=$NF/a[FILENAME]; $++NF=v; print > out}' info file1 file2

将生成更新的文件

$ head file{1,2}.new | column -t

==> file1.new <==
chrm name value new_value
4 a 8 1
3 b 4 0.5

==> file2.new <==
chrm name value new_value
3 g 6 1
5 s 12 2

解释

NR==FNR {a[$1]=$2; next} scan the first file and save the file/value pairs in the associative array

FNR==1 in the header line of each data file

out=FILENAME".new" set a output filename

print $0, "new_value" > out print existing header appended with the new column name

v=$NF/a[FILENAME] for every data line, scale the last field and assign to v

$++NF=v increment number of fields and assign the new computed value to the last field

print > out print the new line to the same file set before

info file1 file2 the list of files should be preceded by the info file

关于linux - 如何根据另一个文件中的相应值来划分列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882838/

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