累计到个体使用awk

huangapple go评论66阅读模式
英文:

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 &#39;
    # Save Original Values
{ pp=$1 }
    # Reverse cumulative values
$1 != -999 &amp;&amp; p != &quot;&quot; &amp;&amp; p != -999 &amp;&amp; $1 &gt;= p { $1 = $1 - p }
    # Print value, save for next line
{ print $1 ; p=pp}
&#39; ifile.txt  &gt; ofile.txt

Single Line:

awk &#39;{ pp=$1 } $1 != -999 &amp;&amp; p != &quot;&quot; &amp;&amp; p != -999 &amp;&amp; $1 &gt;= p { $1 = $1 - p } {  print $1 ; p=pp}&#39; ifile.txt  &gt; ofile.txt

huangapple
  • 本文由 发表于 2020年1月6日 16:45:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定