grep匹配的行和字符串位置 [英] line and string position of grep match

查看:209
本文介绍了grep匹配的行和字符串位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一种方法来输出从一个文件到另一个文件的grep匹配的确切坐标。所以说'模式'包含一个匹配的字符串模式列表。 'Search'是一个包含要搜索的文本的基于行的文本(ascii)文件。



包含:

  grep -onf模式搜索

我得到这行和在这条线上匹配的模式,但不匹配模式匹配的线条,这是我需要的。它不限于使用grep,awk等也很好!



你们可以帮忙吗?

谢谢



Best,

Phil

解决方案

未经测试:

  awk'NR == FNR {strings [$ 0];下一个} {for(string in strings)if((idx = index($ 0,string))> 0)print string,FNR,idx}'file1 file2 

由于你在使用 -f 时使用grep,我假设它是你想匹配的字符串,而不是正则表达式。 / p>

以上只是从第一个文件的内容构建一个字符串数组,然后为第二个文件的每一行寻找每个字符串出现的位置的索引谎言,如果它存在打印字符串,行号和该字符串第一次出现在该行的索引(起始位置)。


I need to find a way to ouput the exact coordinates of a grep match from one file to another. So say 'patterns' contains a list of string patterns to match. 'Search' is a line based text (ascii) file containing the text to search in.

with:

grep -onf patterns search

I get the line and the pattern that matches in this line but not where in the line the pattern matches and this is what I need. It's not restricted to using grep, awk etc. is also fine!

Can you guys help?

Thanks in advance!

Best,

Phil

解决方案

Untested:

awk 'NR==FNR{strings[$0]; next} {for (string in strings) if ( (idx = index($0,string)) > 0 ) print string, FNR, idx }' file1 file2

Since you're using -f with grep I assume it's strings you want to match on, not regexps.

The above just builds an array of strings from the contents of the first file and then for each line of the second file it looks for the index of where each string occurs on that lie and if it exists prints the string, the line number and the index (starting position) of where that string first appears on that line.

这篇关于grep匹配的行和字符串位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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