Applying commands to lists

Very often I need to apply a certain simple function to a list (or more precisely to a string where substrings that I want to treat as separate items are delimited by a new line). Say I need to extract certain numbers from a list of filenames of files containing a certain other string, say stringToBeSearched. A simple solution to get the appropriate list of file names would be

grep -l "stringToBeSearched" *

I then simply want to feed this to another function that takes the substring I want. To try to do this I define for example

 f () { echo $(sed 's/begin-([0-9]*).end/1/' <<<$1) ;}

which should extract digits in a file of for example the format begin-123.end. I would already prefer to avoid defining such a function at all since it won’t be reused, but I can’t seem to find the equivalent of what in Mathematica would be called Pure Functions, i.e. something of the form #1 +#2 & for a anonymous function to add two arguments together.

Applied to a string this function does what I want so the only step remaining is to apply it to the correct list of strings. I thought I would be able to do this using

  grep -l "stringToBeSearched" * | xargs -n1 f

Only this does not seem to work because xargs does not know the function f. The wrong scope I guess. The solution is suggest to be exporting f (https://stackoverflow.com/a/11003457/7238575), but that does not seem to help. Others (https://stackoverflow.com/questions/11003418/calling-shell-functions-with-xargs) suggest we also need to call a new instance of bash.

However, if I try

grep -l "stringToBeSearched" * | xargs -n1 bash -c f

it only prints a list of white lines.

Clearly, there must be a much simpler way to do something as simple as applying a function f to a list.


Example input and output:
There are some files containing the text stringToBeSearched. Say one named begin-1.end and one named begin-2.end. Say these files are hidden among files not containing stringToBeSearched. I want to obtain a list of the numbers in the filenames of those files that do contain stringToBeSearched. So in this case I want to obtain a list containing 1 and 2. Ideally I also have an easy way to apply a function not mentioned above say f2 to these functions. So that in the end I want to be able to run f2 1 and ‘f2 2.


If this is an XY problem I would appreciate an answer explaining why this is not the method at all more than the answer to the technical problem. The main point of the question is not how to find these numbers I am looking for (although I would like an answer to that too). It is to ask what the general method of applying a function to a list is. The specific problem explained above is just one instance of the kind of problem where I require the operation of applying a function to a list. It is meant to illustrate the problem of not being able to apply a function to the list. It is not the main problem itself.