skip to Main Content

I am using sed for this, but it is about the same thing with other regex.

Trying to get the DB_NAME, which in this case would be test. Also, I can’t control if single (‘), or double (") quotes are being used. Spaces may exist… So these are some examples of what I can expect:

define( 'DB_NAME', 'test' );
define('DB_NAME','test');
define( "DB_NAME", "test" );

Here is what I’m using:

sed -E -n "s/define([[:space:]]?.DB_NAME.,[[:space:]]?.(.*).[[:space:]]?);/1/p" file.php

This is the output:

test'
test
test"

With the ? after the last [[:space:]], only the second line returns the expected test. The others have the quote appended.

Why is that? Shouldn’t the . catch the quotes and [[:space:]]? catch a space, if it’s there?

I know I can use:

['|"]

to capture either quotes instead of the dot, but wondering why this is…

2

Answers


  1. You can use awk

    awk -F "['"]*" '{print $4}' file.php
    test
    test
    test
    
    Login or Signup to reply.
  2. The (.*) captures the quote, and the . outside of the parens captures the trailing white space, and then [[:space:]]? matches 0 characters. Try something like this:

     sed -E -n "s/define([[:space:]]?.DB_NAME.,[[:space:]]?['"](.*)['"][[:space:]]?);/1/p"
    input.txt
    test
    test
    test
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search