greediness in sed

前端 未结 5 550
南旧
南旧 2021-01-16 16:14

I want

ereg ($rat, $dog, $cat)

to become

preg_match (\'#\'.$rat.\'#\', $dog, $cat)

To achieve this, I did

相关标签:
5条回答
  • 2021-01-16 16:52

    I rather like Perl regexs (easier to write):

    echo 'ereg ($rat, $dog, $cat)' | perl -pe 's/ereg\s*\(\s*(\$[^,]+),(.+)\)/preg_match("#" . $1 . "#", $2)/g'
    

    or better (for PHP):

    echo 'ereg ($rat, $dog, $cat)' | perl -pe 's/ereg\s*\(\s*(\$[^,]+),(.+)\)/preg_match("#{$1}#", $2)/g'
    

    In sed, it would be:

    echo 'ereg ($rat, $dog, $cat)' | sed -e 's/ereg\s*(\s*\(\$[^,]\+\),\(.\+\))/preg_match("#" . \1 . "#", \2)/'
    

    Too many backslashes!!!

    0 讨论(0)
  • 2021-01-16 17:00

    Just exclude ','...

    echo 'ereg ($rat, $dog, $cat)' | sed "s/ereg\(.*\)(\([^,]*\),/preg_match\1('#'.\2.'#',/g"
    
    0 讨论(0)
  • 2021-01-16 17:05

    Note: This also works if you have multiple instances of ereg ($rat, $dog, $cat) on the same line whereas other answers do not:

    $ echo 'ereg ($rat, $dog, $cat)' | sed "s/ereg\([^(]*\)(\([^,]*\),\([^)]*)\)/preg_match\1('#'.\2.'#',\3/g"
    preg_match ('#'.$rat.'#', $dog, $cat)
    

    Example

    $ echo 'ereg ($rat, $dog, $cat) ereg ($rat, $dog, $cat)' | sed "s/ereg\([^(]*\)(\([^,]*\),\([^)]*)\)/preg_match\1('#'.\2.'#',\3/g"
    preg_match ('#'.$rat.'#', $dog, $cat) preg_match ('#'.$rat.'#', $dog, $cat)
    
    0 讨论(0)
  • 2021-01-16 17:12

    How about:

    $ echo 'ereg ($rat, $dog, $cat)' | sed "s/ereg *(\([^,]*\), \([^,]*\)\([^)]*\))/preg_match('#'.\1.'#', \2\3)/g"
    preg_match('#'.$rat.'#', $dog, $cat)
    
    0 讨论(0)
  • 2021-01-16 17:15
    ~ ross$ echo 'ereg ($rat, $dog, $cat)' | sed -e "s/.*(\([^,]*\),\([^,]*\),\([^)]*\))/preg_match ('#'.\1.'#', \2, \3)/"
    preg_match ('#'.$rat.'#',  $dog,  $cat)
    
    0 讨论(0)
提交回复
热议问题