【问题标题】:Setting a threshold for multiple files in directory为目录中的多个文件设置阈值
【发布时间】:2017-03-01 15:21:20
【问题描述】:

我有一个目录中的文件列表。例如,下面的文件是每个文件的名称,第一行显示(每个文件中还有几行不重要)。

组 1

8 325
quick brown fox jumped
Over the lazy dog

第二组

8 560
There is more content here

第三组

7 650

我想读取每个文件的第一行,检查第一个值是否等于 8,第二个值是否大于 500。如果满足此条件,则将文件名打印到新的文本文件中。

结果

Group2  

我尝试过使用

for f in *.Group; 
do head -n1 *.Group > new-file;
done 

这给了我一个带有标题名称的文件和目录中每个文件的第一行

=> Group1 <=
8 325

=> Group2 <=
8 560

=> Group3 <=
7 650

现在,我想根据阈值过滤文件,但不知道如何将所有标题转换为第一列,将相应的值转换为第二列。然后很容易应用阈值并过滤文件。或者有更好的方法吗?

【问题讨论】:

  • 您的文件也是如此,例如Group1Group1.Group?
  • Group1, group2,.. 等等

标签: awk sed


【解决方案1】:

你可以使用awk:

awk 'FNR==1 && $1==8 && $2>500{print FILENAME}' *.Group > Result

解释:

# FNR contains the number of line of the current(!) input
# file. Check if the conditions are met and print the filename
FNR==1 && $1==8 && $2>500 {
    print FILENAME
}

上述解决方案适用于任何版本的awk。如果你有 GNU awk,你可以利用 nextfile 表达式。使用它,您可以在处理完第一行后跳过输入文件的其余行:

# Check if the conditions are met and print the filename in that case
$1==8 && $2>500 {
    print FILENAME
}

# Skip the remaining lines in the current file and continue
# with the next file
{
    nextfile
}

【讨论】:

  • 所以我检查了文件 awk -F '' '{print NF}' Group1 第一行中的字段数,它显示为 6,所以在这种情况下,解决方案可能有点不同因为它们不仅仅是两个独立的字段。
  • -F '' 将行拆分为单独的字符。 Group1 有 6 个字符,没错。那你什么意思?
  • 很高兴听到这个消息!
猜你喜欢
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
相关资源
最近更新 更多