英文:
Cummulative to individual using awk
问题
以下是您要翻译的代码部分:
awk'{(if $1 != -999 && [$1] >= [$2]),printf "%s\n",$1-$2}' ifile.txt
希望这对您有所帮助。
英文:
I have following datafile where the values are in cumulative to some point (until row1 > row2):
ifile.txt
6
7
10
34
-999
-999
0
2
4
8
12
12
-999
-999
-999
-999
12
13
15
I would like to print all individual values without considering the undefined values (i.e. -999).
My desire output is:
ofile.txt
6
1
3
24
-999
-999
0
2
2
4
4
0
-999
-999
-999
-999
12
1
2
I am trying with awk'{(if $1 != -999 && [$1] >= [$2]),printf "%s\n",$1-$2}' ifile.txt
答案1
得分: 3
这是另一个awk的想法:
$ awk '($1==-999){p=0; print; next}{print $1-p;p=$1}' file
这个想法是使用变量 p
来跟踪前一行的累积值。每当我们遇到值 -999
时,我们将 p
重置为零。p
的值不需要初始化,因为awk假定所有未初始化的变量默认为空字符串 和 值0。
英文:
Here is another awk idea:
$ awk '($1==-999){p=0; print; next}{print $1-p;p=$1}' file
The idea is to keep track of the cumulative value of the previous line with the variable p
. Everytime we hit the value -999
, we reset p
to zero. The value of p
does not need to be initialized as awk assumes that all un-initialized variables are by default an empty string and the value 0.
答案2
得分: 2
你可以使用这个更简单的awk命令:
awk '{print ($1>=p ? $1-p : $1)} {p = ($1==-999 ? 0 : $1)}' file
6
1
3
24
-999
-999
0
2
2
4
4
0
-999
-999
-999
-999
12
1
2
英文:
You may use this much simpler awk:
awk '{print ($1>=p ? $1-p : $1)} {p = ($1==-999 ? 0 : $1)}' file
<p/>
6
1
3
24
-999
-999
0
2
2
4
4
0
-999
-999
-999
-999
12
1
2
答案3
得分: 1
在 awk
中,$1、$2 等表示不同的列,而不是不同的行。
考虑使用额外的变量 p
来跟踪前一个值,以便反转累积值。
awk '
# 保存原始值
{ pp=$1 }
# 反转累积值
$1 != -999 && p != "" && p != -999 && $1 >= p { $1 = $1 - p }
# 打印值,保存供下一行使用
{ print $1 ; p=pp}
' ifile.txt > ofile.txt
单行版本:
awk '{ pp=$1 } $1 != -999 && p != "" && p != -999 && $1 >= p { $1 = $1 - p } { print $1 ; p=pp}' ifile.txt > ofile.txt
英文:
In awk
$1, $2, ... represent different columns, not different rows.
Consider using extra variable p
to track previous value for the purpose of reversing the cumulative values
awk '
# Save Original Values
{ pp=$1 }
# Reverse cumulative values
$1 != -999 && p != "" && p != -999 && $1 >= p { $1 = $1 - p }
# Print value, save for next line
{ print $1 ; p=pp}
' ifile.txt > ofile.txt
Single Line:
awk '{ pp=$1 } $1 != -999 && p != "" && p != -999 && $1 >= p { $1 = $1 - p } { print $1 ; p=pp}' ifile.txt > ofile.txt
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论