我有文件的大量数据,需要以以下格式打印确切的关键字:Filename : Keyword : line number
[注意:需要在整个目录中递归搜索关键字]
例如:我要搜索关键字:abcxyz
文件中的数据如下
abcxyz.fgh
gfhj.abcxyz
i have a book with name abcxyz.sh
where is my brother called : abcxyz.fsdghj raju how are you
afsgdjj kllf
ghjakl ra jksu ldlahlalfb afhkflkaf dbllf jll afl;bnhafl
当我使用以下命令:grep "abcxyz" *.*
时,它将打印我不需要的整行
预期产量:
Filename : abcxyz.fgh : line number
Filename : gfhj.abcxyz : line number
Filename : abcxyz.sh : line number
Filename : abcxyz.fsdghj : line number
分析解答
这应该是awk
的工作,请您尝试按照GNU awk
中显示的示例进行以下操作,编写和测试。请提及绝对路径代替.
,以便在find命令中为任何目录运行它。
所有文件的输出应为filename : matched string(s) : line number
。
您可以运行以下find
命令:
find . -type f -exec awk -f script.awk {} +
其中script.awk
如下:
cat script.awk
BEGIN{ OFS=" : " }
NF{
for(i=1;i<=NF;i++){
if($i~/abcxyz/){
val=(val?val OFS:"")$i
}
}
if(val){
print FILENAME,val,FNR
}
val=""
}
对于您显示的样本(考虑其中的空行),样本输出如下。
Input_file : abcxyz.fgh : 1
Input_file : gfhj.abcxyz : 3
Input_file : abcxyz.sh : 5
Input_file : abcxyz.fsdghj : 7
说明:添加了以上的详细说明。
BEGIN{ OFS=" : " } ##Setting OFS to space colon space in BEGIN section of this program.
NF{ ##Checking condition if line is NOT empty then do following.
for(i=1;i<=NF;i++){ ##Traversing through all field values here.
if($i~/abcxyz/){ ##checking condition if field is matching abcxyz then do following.
val=(val?val OFS:"")$i ##Creating val which has value of current field and keep adding it.
}
}
if(val){ ##Checking condition if val is NOT NULL then do following.
print FILENAME,val,FNR ##Printing FILENAME val and FNR here.
}
val="" ##Nullifying val here.
}
'