Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

linux - Maximum of the differences using shell script or awk

I have several files, each having two columns with some wrong data as large negative values.

file_1.txt

3       4
4       5
2       4
-10023  -9821
4       7
9       1
3       5
3       4

file_2.txt

6       2
4       5
2       4
-98323  -83432
-208932 4
7       17
20      3
20      2

file_3.txt

4       4
2       4
2       4
-129923 -1209923
2       3
12      3
2       4
7       1

I would like to print the maximum of the differences between the column 1 and column 2 in the above files without considering the wrong data. In simple way,

Maximum [ ($1 - $2) file*.txt ]

Desired output

ofile.txt
4
-1
-2
-99999
-1
9
17
18
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following works with your sample input in a single pass (Assuming all data files have the same number of lines):

$ awk '$1 > -1000 && $2 > -1000 {
         d = $1 - $2
         if (FNR in diffs) {
           if (diffs[FNR] < d)
             diffs[FNR] = d
         } else {
           diffs[FNR] = d
         }
       }
       END {
         for (n = 1; n <= FNR; n++) {
           if (n in diffs)
             print diffs[n]
           else 
             print -99999
         }
       }' file_*.txt
4
-1
-2
-99999
-1
9
17
18

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...