awk - 打印一个文件的行数和另一个文件的总数
问题描述
我有一个名为 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
解决方案
编辑:由于 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.
推荐阅读
- apache-spark - 为什么我不断收到错误消息:遇到错误:尝试在 EMR 的核心实例之一上加载模型时未定义名称“tf”?
- anypoint-studio - 在 Mule4 中将 Http 响应数据设置为变量
- java - 一次更新多个 SQL 表 Java
- c# - 我应该通过 Mutex 排队 Nmodbus4 RTU 连接吗?
- angular - 如何在 Angular 10 应用程序中等待 rxjs/fromEvent() 的结果
- javascript - Chrome 扩展:获取 URL 时扩展上下文无效
- r - Bookdown preview_chapter
- python - Scrapy Xpath 选择器返回部分文本
- linux - 如何删除已编译的 Citadel?
- ios - Firebase 云消息传递的 FCM 令牌有时未注册