1

I have number of text files which has 70000 rows and 2 column. I would like to sum entries of 2nd column from 40000 to 70000 row and value of sum is to written to new text file.

e.g:-Suppose

Data1_old.txt

  .5
  .6
  .3
  .5
  .9

Data2_old.txt

  .3
  .9
  1.2
  .8
  .6

and I would like to add the value of row 3 to 5 of each file and write that to New_Data.txt

So, New_data.txt should look like this

  1.7
  2.6

I know how to read and write to text file. I tried using awk command but wasn't able to specify rows for which i needed to sum rows specific the values. I would like to know which command to use for sum and how to write that sum value to text file.

3
  • You can get a range of rows (or lines) with awk using FNR. For example, you can the values from line 3 to 5 with: awk 'FNR>=3 && FNR<=5' yourfile.txt For more information about awk command, type in the terminal man awk Apr 2, 2022 at 5:54
  • Do you really have those leading 1., 2., apparent line numbers in your input and do you really want them in your output? If the answer is no then remove them from your example.
    – Ed Morton
    Apr 2, 2022 at 12:52
  • I am sorry for that, I didnt needed them shouldn't have added them.
    – Yash54
    Apr 3, 2022 at 12:13

1 Answer 1

1

This might be what you want, using GNU awk for ENDFILE:

awk '40000<=FNR && FNR<=70000{sum+=$NF} ENDFILE{print sum+0; sum=0}' Data*.txt > New_data.txt

If you really do want your output to start with 1., 2., etc. line numbers then just tweak it to:

awk '40000<=FNR && FNR<=70000{sum+=$NF} ENDFILE{print  ARGIND"." sum+0; sum=0}' Data*.txt > New_data.txt
1
  • 1
    This works well i will modify my previous code. I initially used sed command to delete the unwanted rows then used awk command to sum the columns and edited those values to new file. But your solution works well and is more understandable. Thanks @Ed Morton
    – Yash54
    Apr 3, 2022 at 12:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .