用awk /查找输出结果和文件名 [英] Using awk/find to output result and file name

查看:349
本文介绍了用awk /查找输出结果和文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实例三个文件的数据。

fileOne.txt

YYY >>
 yyy one
 yyy two
 yyy three
<<

ZZZ >>
 zzz one
 zzz two
 zzz three
<<

fileTwo.txt

XXX >>
 xxx one
 xxx two
 xxx three
<<

fileThree.txt

XXX >>
 xxx one
 xxx two
 xxx three
<<

ZZZ >>
 zzz one
 zzz two
 zzz three
<<

我使用awk开始分隔符的文件输出部分( XXX )和结束分隔符(&LT;&LT; )。这工作:

I am using awk to output portions of the file between start delimiter (XXX) and end delimiter (<<). This works:

awk '/XXX/,/<</' /d/Temp/temp/*.txt

结果

XXX >>
 xxx one
 xxx two
 xxx three
<<
XXX >>
 xxx one
 xxx two
 xxx three
<<

但我要输出的文件名了。查找排序的作品,但它结束了印刷全部文件名。

find /d/Temp/temp/ -type f -name "*.txt" -print -exec awk '/XXX/,/<</' {} \;

结果

/d/Temp/temp/fileOne.txt
/d/Temp/temp/fileThree.txt
XXX >>
 xxx one
 xxx two
 xxx three
<<
/d/Temp/temp/fileTwo.txt
XXX >>
 xxx one
 xxx two
 xxx three
<<

我怎么能修改此命令只输出匹配的文件名?

How can I modify this command to only output the matched file names?

推荐答案

用awk

awk '/XXX/,/<</{print a[FILENAME]?$0:FILENAME RS $0;a[FILENAME]++}' *.txt

说明:

/XXX/,/<</                      # output portions of the file between start delimiter (XXX) and end delimiter (<<). 
a[FILENAME]?                    # assign filename as key to array `a`, determine whether it is the true (>0) or fails (0 or null)
a[FILENAME]?$0:FILENAME RS $0   # if true, print the line only, if fail, print filename and the current line
a[FILENAME]++                   # increase the value of array a[FILENAME]

这篇关于用awk /查找输出结果和文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆