TransWikia.com

print the count of the lines from one file and total from another file

Stack Overflow Asked by Rama on October 16, 2020

I am having a directory called Stem, in that stem directory I am having two files called result.txt and title.txt as below:

result.txt:

Column1     Column2     Column3     Column4
----------------------------------------------------------
Setup       First       Second      Third
Setdown     Fifth       Sixth       Seven   
setover     Eight       Nine        Ten
Setxover    Eleven      Twelve      Thirteen
Setdrop     Fourteen    Fifteen     sixteen

title.txt:

Column1     Column2     Column3     Column4
----------------------------------------------------------
result        20           40         60
result1       40           80         120
Total:        60           120        180

I need to count the number of lines except first two in the first file(result.txt) and from the second file(title.txt) I need the data from the line Total (Column3), I need to get the output like below:

Stem : 5    120

I used this script but am not getting the exact output.

#!/bin/bash
for d in stem;
do
echo "$d"
File="result.txt"
File1="title.txt"
awk 'END{print NR - 2}' "$d"/"$File" 
awk '/Total/{print $(NF-1);exit}' "$d"/"$File1"
done

One Answer

EDIT: Since OP's question was not clear which value exactly needed, previous answer provides sum of 2nd columns, in case OP needs to get 2nd last field value of line which has Total: keyword in it then try following:

awk '
FNR==NR{
  tot=FNR
  next
}
/Total:/{
  sum=$(NF-1)
}
END{
  print "Stem : ",tot-2,sum+0
}
' result.txt title.txt

Explanation: Adding detailed explanation for above.

awk '                              ##Starting awk program from here.
FNR==NR{                           ##Checking condition FNR==NR which will be TRUE when result.txt is being read.
  tot=FNR                          ##Creating tot which has value of FNR in it.
  next                             ##next will skip all further statements from here.
}
/Total:/{                          ##Checking condition if line contains Total: then do following.
  sum=$(NF-1)                      ##Creating sum which has 2nd last field of current line.
}
END{                               ##Starting END block of this program from here.
  print "Stem : ",tot-2,sum+0      ##Printing Stem string tot-2 and sum value here.
}
' result.txt title.txt            ##Mentioning Input_file names here.

Correct answer by RavinderSingh13 on October 16, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP