Doing a regex matched on a fixed string with perl or grep


Enter Your Query:
Use '%' for wildcards and quotes for "exact phrases"


Top Level » System Level » Perl

Doing a regex matched on a fixed string with perl or grepLast Modified: Nov 18, 2015, 1:20 am
Many times we need to swap strings or look for a string, but in webhosting, very often, these string matches contain period/dots.   Perl/grep are powerful in that they have special characters for matching, but unfortunately dot are wildcards, so any domain you're trying to match typically has to be escaped by adding a \ character before the dot.   When working with large number of matches or scripting, it's easier to simply tell perl or grep to match a fixed string, so no characters are treated as "special".

Let's create a test.txt file with the lines:

server.domain.com
serverAdomainBcom
server1domain2com


grep


When you run the following you get 3 results, which might not be what you want:

[root@test ~]# grep server.domain.com test.txt.orig
server.domain.com
serverAdomain.com
server1domain2com

so we can add the -F option, so it's an exact string:

[root@test ~]# grep -F server.domain.com test.txt.orig
server.domain.com


perl


With a perl regex, it doesn't have the command line option, but it has the Q and E options, which mean "everything after Q and before E should not be escaped, making life much easier for doing an exact match.

If you want to swap server.domain.com with something.else.com, it should be:

[root@test ~]# perl -pi -e 's/^\Qserver.domain.com\E\$/something.else.com/' test.txt; cat test.txt
something.else.com
serverAdomain.com
server1domain2com

We use the ^ to match the start of the line, and \$ to match the end of the line for this example.
But if you value was within a line (other values before and after), you wouldn't use them.

© 2018 JBMC Software, Suite 173  3-11 Bellerose Drive, St Albert, AB  T8N 1P7  Canada.  Mon-Fri 9AM-5PM MST