首页 > 解决方案 > 打印一个文件的行数和另一个文件的总数

问题描述

我有一个名为 Stem 的目录,在该 Stem 目录中,我有两个名为 result.txt 和 title.txt 的文件,如下所示:

结果.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

标题.txt:

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

我需要计算第一个文件(result.txt)和第二个文件(title.txt)中除前两行之外的行数我需要Total(Column3)行中的数据,我需要得到如下输出:

Stem : 5    120

我使用了这个脚本,但没有得到确切的输出。

#!/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

标签: awk

解决方案


编辑:由于 OP 的问题不清楚究竟需要哪个值,因此先前的答案提供了第二列的总和,以防 OP 需要获取其中包含Total:关键字的行的第二个最后一个字段值,然后尝试以下操作:

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

说明:为上述添加详细说明。

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.

推荐阅读