Es Noguera
Es Noguera

Reputation: 446

How to find a specific string and take it as an entry to a new find in the same file

  1. I need to find a string into many files at multiples folders with a regular expression. The string can be in multiple files.
  2. When I find it, take the string and search again in the same file but now with the specific string.
  3. And to return the name of the file where the string was found and the string itself.

Think about doing with grep command to find the string and then looping the output but anybody has any idea to solve it better?

for example:

Look in file.js the pattern regex: SearchMethod\(([a-zA-Z] *)\)

Once found, look for the previous capture at the same file with another regex capture=('[a-zA-Z']') and will find something like the following:

From capture='value';

get the string 'value'.

And return the string 'value' and the name of file to which it belongs.

Upvotes: 0

Views: 61

Answers (1)

glenn jackman
glenn jackman

Reputation: 246807

First, some sample data:

$ cat file
capture='foo'
capture='bar'
capture='baz'
capture='foobar'
SearchMethod(foo)
SearchMethod(bar)
SearchMethod(qux)

Then, get the "search strings", the SearchMethod parameters

$ search_strings=$( grep -oP 'SearchMethod\(\K\w+' file | paste -s -d'|' )
$ echo "$search_strings"
foo|bar|qux

Then, search for the "capture" words, with the filename in the output

$ grep -HoP "capture='\\K($search_strings)\\b" file
file:foo
file:bar

The \b gives you a word-boundary constraint, which is why foobar does not show up in the final output. Requires GNU grep, which you get on Linux.

Upvotes: 1

Related Questions