jasmaar
jasmaar

Reputation: 225

Grep or in part of a string

Good day All,

A filename can either be

  1. abc_source_201501.csv Or,
  2. abc_source2_201501.csv

Is it possible to do something like grep abc_source|source2_201501.csv without fully listing out filename as the filenames I'm working with are much longer than examples given to get both options?

Thanks for assistance here.

Upvotes: 1

Views: 266

Answers (4)

rici
rici

Reputation: 241721

The simplest possibility is to use brace expansion:

grep pattern abc_{source,source2}_201501.csv

That's exactly the same as:

grep pattern abc_source{,2}_201501.csv

You can use several brace patterns in a single word:

grep pattern abc_source{,2}_2015{01..04}.csv

expands to

grep pattern abc_source_201501.csv abc_source_201502.csv \
             abc_source_201503.csv abc_source_201504.csv \
             abc_source2_201501.csv abc_source2_201502.csv \
             abc_source2_201503.csv abc_source2_201504.csv

Upvotes: 0

tripleee
tripleee

Reputation: 189387

If you are asking about patterns for file name matching in the shell, the extended globbing facility in Bash lets you say

shopt -s extglob
grep stuff abc_source@(|2)_201501.csv

to search through both files with a single glob expression.

Upvotes: 0

folkol
folkol

Reputation: 4883

You can use Bash globbing to grep in several files at once.

For example, to grep for the string "hello" in all files with a filename that starts with abc_source and ends with 201501.csv, issue this command:

grep hello abc_source*201501.csv

You can also use the -r flag, to recursively grep in all files below a given folder - for example the current folder (.).

grep -r hello .

Upvotes: 0

Reuben L.
Reuben L.

Reputation: 2859

Use extended regex flag in grep.

For example:

grep -E abc_source.?_201501.csv

would source out both lines in your example. You can think of other regex patterns that would suit your data more.

Upvotes: 2

Related Questions