Reverse regex logic


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Reverse regex logic
# 1  
Old 09-12-2011
Reverse regex logic

Hi,

I'm trying to reverse regex logic to use it in grep command. I would like to grep a string within a file that contains regex.
For example
file example.txt contains line:
match*

And I would like to find it using
grep match123 example.txt

Is it possible?
Thank you very much for all answers!

Regards,
Igor
# 2  
Old 09-12-2011
That exact command won't work of course, but perhaps:

Code:
echo match123 | grep -f matchfile

The -f tells it to interpret matchfile file as a file full of regexes, one per line.
# 3  
Old 09-12-2011
Hi Corona688, thanks for quick reply!

It's not working this way. Problem is that I nowhere found single example of same logic (to match exact string with regex or any wildcard). Maybe I just expect too much...
# 4  
Old 09-12-2011
Ah. match* If interpreted as a regex, the * here matches 0 or more h chars, so you'd match 'match', 'matchh', 'matchhhh' and so forth. If this isn't what you want, then this isn't a regex, and grep can't handle it. It looks more like a shell glob...

To match one or more of any chars your string would need to be match.*

---------- Post updated at 09:21 AM ---------- Previous update was at 09:15 AM ----------

If you have BASH or KSH:

Code:
STR="match123"

OLDIFS="$IFS"
IFS=""
while read LINE
do
        [ -z "$LINE" ] && continue # Ignore blank lines
        [[ "${STR}" == $LINE ]] && echo "$LINE"
done < globfile
IFS="$OLDIFS"

Lines like match* should match the "match123". atch* wouldn't. *atch* still would.

Last edited by Corona688; 09-12-2011 at 01:27 PM..
# 5  
Old 09-12-2011
Hi,
Try this untested one,
Code:
grep "match\*" file

Cheers,
Ranga:-)
Login or Register to Ask a Question

Previous Thread | Next Thread

2 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Using a reverse regex to create a number

Hi all, I'm having an issue about a code i should write... I have a file... with the following numbers in regex format: $ cat file_regex.txt 55500508007* 55500218200* 182936* 182929* 4179* 381* 550069341* So this is a file cointaing some regex... so for each regex i need to... (3 Replies)
Discussion started by: poliver
3 Replies

2. UNIX for Dummies Questions & Answers

using sed and regex to reverse order???

so i have been trying to learn how to manipulate text on my own and have gotten stumped... let's say i have a text file that says (highly simplified): people ordinary How would swap the order of the words.. I know i need to use sed and some kind of back reference but cannot make it... (2 Replies)
Discussion started by: urtherhoda
2 Replies
Login or Register to Ask a Question