我希望使用awk或sed搜索文件,当遇到特定的字母/子字符串时,它会在它之前插入一个新行。我的文件示例如下:
"ABC" "3 0 1 0 1" "ABC" "0 2 0 2 0"
因此,当它找到字符串ABC时,它会插入一个新行,因此输出如下所示:
"ABC" "3 0 1 0 1"
"ABC" "0 2 0 2 0"
然后,一旦完成此步骤,我想将这些值相加,得到如下输出:
"ABC" "3 0 1 0 1" "5"
"ABC" "0 2 0 2 0" "4"
答案 0 :(得分:0)
如果您有GNU awk
,那么这将解决问题:
BEGIN {
FPAT="\"[^\"]+\"" # Describe the field pattern
}
{
for (i=1;i<=NF;i+=2) { # Loop over all the fields
n=split($(i+1),x,/[\" ]/) # Split the numbers fields
s = 0 # Variable for the sum of number field
for (j=2;j<n;j++) { # Loop over each number in field
s += x[j] # Summation
}
print $i,$(i+1),"\""s"\"" # Print field pairs and sum
}
}
将其保存到script.awk
等文件中并运行如下:
$ awk -f script.awk file
"ABC" "3 0 1 0 1" "5"
"ABC" "0 2 0 2 0" "4"
答案 1 :(得分:0)
为简单起见,我会在2遍中完成:
$ cat file
"ABC" "3 0 1 0 1" "ABC" "0 2 0 2 0"
$ awk -v t='"ABC"' '{gsub(" *"t,"\n"t)}1' file |
awk -F\" 'NF{split($4,a,/ /); s=0; for (i in a) s+=a[i]; print $0, FS s FS}'
"ABC" "3 0 1 0 1" "5"
"ABC" "0 2 0 2 0" "4"