chris yo
chris yo

Reputation: 1277

sed error sed: -e expression #1, char 23: invalid reference \1 on `s' command's RHS

I am getting an error with sed:

sed: -e expression #1, char 23: invalid reference \1 on `s' command's RHS

Here is my script:

result=`$(PERL) parse.pl report.log`;   \
echo $$result | sed "s/.*([a-zA-Z0-9._]*).*/\1/p";

Basically, the output of my perl script is something like this:

ERR: dir/out/file/report/temp.log (23): some error message here

What I expect sed to do is to get the path which is dir/out/file/report/temp.log.

But I am stuck on this error: sed: -e expression #1, char 23: invalid reference \1 on `s' command's RHS

what am i missing?

Upvotes: 2

Views: 1806

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

It is because, sed treats ( as character pattern by default. You need to either,

  • Escape the paranthesis,

    echo $$result | sed "s/.*\([a-zA-Z0-9._]*\).*/\1/p";
    
  • User extended regular expressions using -E

    echo $$result | sed -E "s/.*([a-zA-Z0-9._]*).*/\1/p";
    

The regex that you have will not be sufficient to get the directory name from the string. Instead you can write

$ sed -E 's/ERR: ([^ ]*).*/\1/g'

Example

$ echo "ERR: dir/out/file/report/temp.log (23): some error message here" | sed -E 's/ERR: ([^ ]*).*/\1/g'
dir/out/file/report/temp.log

Upvotes: 2

Related Questions