gpt4 book ai didi

linux - 使用管道命令创建 AWK For 循环

转载 作者:太空狗 更新时间:2023-10-29 11:43:29 24 4
gpt4 key购买 nike

下面的命令正是我需要它做的它检查列中是否存在字符串,如果不存在则添加逗号。

awk -F, -v OFS=, '!/Reading Comprehension/ { $5 = $5 "," } 1' somefile.csv \
| awk -F, -v OFS=, '!/Sentence Skills/ { $6 = $6 "," } 1' \
| awk -F, -v OFS=, '!/Arithmetic/ { $7 = $7 "," } 1' \
| awk -F, -v OFS=, '!/College Level Math/ { $8 = $8 "," } 1' \
| awk -F, -v OFS=, '!/Elementary Algebra/ { $9 = $9 "," } 1' > endfile.csv

如何将这个串联/管道命令转换为 awk 循环?

我是这样想的:

awk -F, OFS=,
i = Reading Comprehension, Sentence Skills, Arithmetic, College Level Math, Elementary Algebra
j = 5,6,7,8,9
{for ((i<=NF; j<=NF) '!/i/ { $j = $j "," } 1')}

示例输入:

last,first,A00XXXXXX,1888-01-01,2015-05-13,Elementary Algebra 34
last,first,A00XXXXXX,1888-01-01,2015-05-13,Reading Comprehension 97,Sentence Skills 104,College Level Math 76,Elementary Algebra 115
last,first,A00XXXXXX,1888-01-01,2015-05-13,Sentence Skills 104,Arithmetic 08,College Level Math 76,Elementary Algebra 115
last,first,A00XXXXXX,1888-01-01,2015-05-13,College Level Math 76,Elementary Algebra 115
last,first,A00XXXXXX,1888-01-01,2015-05-13,Sentence Skills 104,Elementary Algebra 115

示例输出:

last,first,A00XXXXXX,1888-01-01,2015-05-13,,,,,Elementary Algebra 34
last,first,A00XXXXXX,1888-01-01,2015-05-13,Reading Comprehension 97,Sentence Skills 104,Arithmetic 08,College Level Math 76,Elementary Algebra 115
last,first,A00XXXXXX,1888-01-01,2015-05-13,,Sentence Skills 104,,College Level Math 76,Elementary Algebra 115
last,first,A00XXXXXX,1888-01-01,2015-05-13,,,,College Level Math 76,Elementary Algebra 115
last,first,A00XXXXXX,1888-01-01,2015-05-13,,Sentence Skills 104,,,Elementary Algebra 115

我仍在学习 AWK,对如何执行 awk 循环只有部分了解。

任何帮助将不胜感激,并且对答案的解释真的很棒。

最佳答案

这个答案假定每个类别中的第一个词是唯一的:

awk -F, -v OFS=, '
{
delete val # clear the previous values if any
for (i=6; i<=NF; i++) {
split($i, a, " ")
val[a[1]] = $i # a[1] is the first space-separated word
}
print $1,$2,$3,$4,$5, val["Reading"], # null values are OK
val["Sentence"],
val["Arithmetic"],
val["College"],
val["Elementary"]
}
' input

关于linux - 使用管道命令创建 AWK For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31008106/

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