Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PCRE Regex to SED

Tags:

regex

sed

pcre

I am trying to take PCRE regex and use it in SED, but I'm running into some issues. Please note that this question is representative of a bigger issue (how to convert PCRE regex to work with SED) so the question is not simply about the example below, but about how to use PCRE regex in SED regex as a whole.

This example is extracting an email address from a line, and replacing it with "[emailaddr]".

echo "My email is [email protected]" | sed -e 's/[a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4}/[emailaddr]/g' 

I've tried the following replace regex:

([a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4}) [a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4} ([a-zA-Z0-9]+[@][a-zA-Z0-9]+[.][A-Za-z]{2,4}) [a-zA-Z0-9]+[@][a-zA-Z0-9]+[.][A-Za-z]{2,4} 

I've tried changing the delimited of sed from s/find/replace/g to s|find|replace|g as outlined here (stack overflow: pcre regex to sed regex).

I am still not able to figure out how to use PCRE regex in SED, or how to convert PCRE regex to SED. Any help would be great.

like image 317
Sugitime Avatar asked Jul 18 '14 19:07

Sugitime


People also ask

Can you use regex in sed?

The sed command has longlist of supported operations that can be performed to ease the process of editing text files. It allows the users to apply the expressions that are usually used in programming languages; one of the core supported expressions is Regular Expression (regex).

Does sed use Perl regex?

Perl supports every feature sed does and has its own set of extended regular expressions, which give it extensive power in pattern matching and processing.

Does grep use PCRE?

grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE), and Perl-compatible (PCRE).

What regex engine does sed use?

1 Answer. Show activity on this post. Both sed and grep by default understand the GNU Basic Regular Expressions notations which is an implementation of POSIX Basic Regular Expressions standard.


2 Answers

Want PCRE (Perl Compatible Regular Expressions)? Why don't you use perl instead?

perl -pe 's/[a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4}/[emailaddr]/g' \     <<< "My email is [email protected]" 

Output:

My email is [emailaddr] 

Write output to a file with tee:

perl -pe 's/[a-zA-Z0-9]+[@][a-zA-Z0-9]+[\.][A-Za-z]{2,4}/[emailaddr]/g' \     <<< "My email is [email protected]" | tee /path/to/file.txt > /dev/null 
like image 200
Rockallite Avatar answered Sep 23 '22 00:09

Rockallite


Use the -r flag enabling the use of extended regular expressions. ( -E instead of -r on OS X )

echo "My email is [email protected]" | sed -r 's/[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]{2,4}/[emailaddr]/g' 

Ideone Demo

like image 22
hwnd Avatar answered Sep 23 '22 00:09

hwnd