3

Let's say I have n files with names like link123.txt, link345.txt, link645.txt, etc.

I'd like to grep a subset of these n files for a keyword. For example:

grep 'searchtext' link123.txt link 345.txt ...

I'd like to do something like

grep 'searchtext' link[123\|345].txt

How can I mention the filenames as regex in this case?

codewario
  • 19,553
  • 20
  • 90
  • 159
Eternal Learner
  • 3,800
  • 13
  • 48
  • 78
  • In simple command lines, you have only filename globbing, which is a crippled kind of regex that can't handle the example you've given. You can probably write a bash script that accepts a program name (like `grep`) and a regex and does what you want. – Gene Sep 27 '17 at 01:05

4 Answers4

5

you can use find and grep together like this

find . -regex '.*/link\(123\|345\).txt' -exec grep 'searchtext' {} \;

Thanks for ghoti's comment.

CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • As you've proposed it, this answer suffers from the same ails as [parsing ls](http://mywiki.wooledge.org/ParsingLs). If you must use `xargs`, consider find's `-print0` option along with `xargs -0`. Or better yet, use `find .. -exec`, either the traditional way or with `\+` as the command terminator so that only a single instance of `grep` needs to be run. – ghoti Sep 27 '17 at 02:36
4

You can use the bash option extglob, which allows extended use of globbing, including | separated pattern lists.

@(123|456)

Matches one of 123 or 456 once.

shopt -s extglob
grep 'searchtext' link@(123|345).txt
shopt -u extglob
Will Barnwell
  • 4,049
  • 21
  • 34
0

I think you're probably asking for find functionality to search for filenames with regex.

As discussed here, you can easely use find . -regex '.*/link\([0-9]\{3\}\).txt' to show all these three files. Now you have only to play with regex.

PS: Don't forget to specify .*/ in the beginning of pattern.

tonyamjr
  • 11
  • 6
0

It seems, you don't need regex to determine the files to grep, since you enumerate them all (well, actually you enumerate the minimal unique part without repeating common prefix/suffix).

If regex functionality is not needed and the only aim is to avoid repeating common prefix/suffix, then simple iterating would be an option:

for i in 123 345 645; do grep searchpattern link$i.txt; done

Frank Neblung
  • 3,047
  • 17
  • 34