Skip to content

02.Data extraction *

Here is a file containing some data

data.dat

23 34 567 3 4556 345 22 45 6
34 5 677 787 234 124 5 5 47
1 34 98 45 24 333 345 121 17
100 345 48 65 90 345 665 12
55 73 34 33 23 25 234 17 19

1) Write a script to print the largest number from each line.

output:

4556
787
345
665
234

Possible solution
awk '{max=$1; for (i=2;i<=NF;i++) { if ($i>max) max=$i } ; print max}' data.dat

2) ... to print the sum of all numbers on each line.

output:

5601
1918
1018
1670
513

Possible solution
awk '{sum=0; for (i=1;i<=NF;i++) { sum=sum+$i } ; print sum}' data.dat

3) ... to print new data in which all numbers smaller than 55 are replaced with 0 (zero).

output:

0 0 567 0 4556 345 0 0 0 
0 0 677 787 234 124 0 0 0 
0 0 98 0 0 333 345 121 0 
100 345 0 65 90 345 665 0 
55 73 0 0 0 0 234 0 0

Possible solution inspired by Jessica De Loma
awk '{ for(i=1;i<=NF;i++){if($i < 55) $i=0 } print $0 }' data.dat