Reputation: 151
I want to be able to check if a variable containing a string matches a regular expression pattern. I know how to do this with a file using grep
but I want to be able to do it using just a string.
For example to find if a variable contains a file name for a .gif I want to be able to do something along the lines of this.
$ STRING=image.gif
$ grep "\.gif$" $STRING
When I run this I get this error.
grep: image.gif: No such file or directory
Is there a way I can get grep
treat "image.gif" as the string I want to search rather than the name of a file?
Upvotes: 0
Views: 928
Reputation: 4267
You can use a bash "here string" to grep from a variable:
grep '\.gif$' <<< "$STRING"
Upvotes: 4
Reputation: 12050
The easiest way:
echo "$STRING" | grep "\.gif$"
Since grep
is capable of reading from stdin
you can adapt this to any number of situations (including file IO with cat
, though that's generally a bad idea because streaming is more efficient).
Upvotes: 2