Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep multiple files using regex for specifying filenames to search for

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?

like image 354
Eternal Learner Avatar asked Sep 15 '25 20:09

Eternal Learner


2 Answers

you can use find and grep together like this

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

Thanks for ghoti's comment.

like image 134
CS Pei Avatar answered Sep 17 '25 13:09

CS Pei


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
like image 45
Will Barnwell Avatar answered Sep 17 '25 12:09

Will Barnwell