2

I have a txt/log file which has data- cat sample.log/(.txt)

500,3,2   

there is script running which overwrite the value in sample.log. Instead of overwrite/or generating a new line I want the data to be get sum up with its respective row.

Example:

Sample.log -500,3,1  
Script out- 600,4,3

Final output that needs to be stored in sample.log

1100,7,4

Every time the script run it keeps on adding the respective value.

Please help me to get this output.

1
  • Is it the value -500 in sample.log or this is typo? Commented Jan 9, 2020 at 11:59

2 Answers 2

1

This is a way to do it using GNU awk where the script is called script.sh and the existing total file is called /tmp/sample.log:

script.sh|\
cat /tmp/sample.log -|\
awk -F, '{for (f=1;f<=NF;f++) TOT[f]+=$f} END {for (f=1;f<length(TOT);f++) printf TOT[f]","; print TOT[length(TOT)]}' >/tmp/sample1.log
mv -f /tmp/sample1.log /tmp/sample.log

The output from script.sh is combined (put as a line under) the existing sample.log and these two lines are then summed in awk and the result used to replace sample.log

This will work with any number of fields (don't have to be consistent). The delimiter is set to be a comma but this could easily be changed.

9
  • You do not need cat, sample awk '{}' filename do the same Commented Jan 9, 2020 at 12:39
  • cat is to combine the output from the script and the file so in this case just using awk '{}' filename does not do the same Commented Jan 9, 2020 at 12:56
  • Thanks It is working!! but one issue is when we use mv command it pops us to overwrite it .... mv: overwrite .... How to always put this as yes. Commented Jan 9, 2020 at 12:58
  • 1
    I've edited it to use mv -f as suggested by Romeo Ninov Commented Jan 9, 2020 at 13:01
  • 1
    Thanks a lot guys... !!!! You made my day... Cheers Commented Jan 9, 2020 at 13:03
1

Tried with below steps

sh script >scriptout
cat sample.log scriptout|awk -F ","  'BEGIN{sum=0;kum=0;jum=0} OFS =","{sum=sum+$1}{kum=kum+$2}{jum=jum+$3}END{print sum,kum,jum}' > final_out
mv final_out sample.log

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.