Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any named regular expression capture for grep?

Tags:

regex

bash

i'd like to know if its possible to get named regular expression with grep -P(linux bash) from a non formatted string? well.. from any string

For example: John Smith www.website.com [email protected] jan-01-2001 to capture as

$name
$website
$email
$date

but it seems I cant pass any variables from output?

echo "www.website.com" | grep -Po '^(www\.)?(?<domain>.+)$' | echo $domain

has no output

like image 497
Shirker Avatar asked Dec 05 '25 14:12

Shirker


1 Answers

no. grep is a process. you are talking about environment propagation from child to parent. that's forbidden.

instead, you can do

DATA=($your_line)

then take name=DATA[0] so and forth.

or another way using awk:

eval "`echo $your_line | awk '
    function escape(s)
    {
        gsub(/'\''/,"'\''\"'\''\"'\''", s);
        s = "'\''"s"'\''";
        return s;
    }
    { 
        print "name="escape($1);
        print "family_name="escape($2);
        print "website="escape($3);
        print "email="escape($4);
        print "date="escape($5);
    }'`"

the sense here is to propagate the info via stdout and eval it in the parent environment.

notice that, here, escape function will escape any string correctly such that nothing will be interpreted wrongly(like the evil of quotes).

following is the output from my jessie:

name='John'
family_name='Smith'
website='www.website.com'
email='[email protected]'
date='jan-01-2001'

if the family name is O'Reilly, the eval result will still be correct:

name='John'
family_name='O'"'"'Reilly'
website='www.website.com'
email='[email protected]'
date='jan-01-2001'
like image 106
Jason Hu Avatar answered Dec 07 '25 07:12

Jason Hu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!