简体   繁体   English

如何使用多个字段分隔符或多个 awk 来处理列

[英]How can I use multiple field separators or multiple awk to process columns

I have a tab separated file which looks like the following我有一个制表符分隔的文件,如下所示

John  1,0   3,2   5,6
Mike  3,2    4,5   0,0
James 3,0    5,3   4,5

I would like to add all the first elements of 3 fields and add second elements of 3 fields output the following我想添加 3 个字段的所有第一个元素并添加 3 个字段的第二个元素输出以下

John 9,8
Mike 9,7
James 12,8 

Is there is a solution in awk where I can use multiple field separators? awk 中是否有可以使用多个字段分隔符的解决方案?

You can use multiple delimiters in awk :您可以在awk使用多个分隔符:

awk -F '[\t,]+' -v OFS='\t' '{print $1, ($2+$4+$6) "," ($3+$5+$7)}' file

John    9,8
Mike    7,7
James   12,8

I don't know about awk but here's a (boring) solution with bash :我不知道awk但这是一个(无聊的) bash解决方案:

while read -r name f1 f2 f3; do
    s1=$((${f1%,*}+${f2%,*}+${f3%,*}))
    s2=$((${f1#*,}+${f2#*,}+${f3#*,}))
    echo "$name $s1,$s2"
done < input.txt
$ awk -F'[\t,]' '{delete s; for (i=2;i<=NF;i++) s[i%2]+=$i; print $1 "\t" s[0] "," s[1]}' file
John    9,8
Mike    7,7
James   12,8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 awk中的多个字段分隔符 - multiple Field Separators in awk 我们可以使用AWK和gsub()处理带有多个冒号“:”的数据吗? 怎么样? - Can we use AWK and gsub() to process data with multiple colons “:” ? How? awk:致命:设置多个字段分隔符时正则表达式无效 - awk: fatal: Invalid regular expression when setting multiple field separators 当有多个字段分隔符时,使用 AWK 忽略字段中的逗号 - Ignoring commas within fields using AWK when there are multiple field separators 如何告诉 Pandas read_csv 使用多个空格作为分隔符而不是单个空格? - How can I tell Pandas read_csv to use multiple whitespaces as separators but not single whitespaces? 如何使用awk匹配多个变量模式? - How do I use awk to match multiple variable patterns? 在awk中打​​印匹配的字段分隔符 - Print matched field separators in awk 如何在 JavaScript 中拆分具有多个分隔符的字符串? - How do I split a string with multiple separators in JavaScript? 如何排除正则表达式中分隔符之间的多行? - How to exclude multiple lines between separators in regex? 如果使用sed或awk行中的字段分隔符数为5,如何在第三个字段之后插入附加字段 - How to insert additional field after third field if number of field separators in line is 5 using sed or awk
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM