2010-05-03 11:15
浏览 32


i have some old php files which i'd like to convert to use gettext. those files have a content like this :

$LD = 'Some String';
$Another = 'some other ~n~ string';

i have to substitute all the $LD, $Another in the files where they are declared with something like :

_('Some string');

hacking a bit a created some sort of regexp to find the declarations, my aim was to use sed and awk to do the replaces..but i don't have any clue on how to do those substitutions ...

any help ...

图片转代码服务由CSDN问答提供 功能建议

我有一些旧的php文件,我想转换为使用gettext。 those文件有类似的内容 这个:

  $ LD ='Some String'; 
 $ Another ='some other~n~string'; 

我必须在声明它们的文件中替换所有$ LD,$ Another:

  _('Some string'); \  n   

黑客攻击有点创建某种regexp来查找声明, 目标是使用sed和awk来替换..但我不知道 对于如何进行这些替换有任何线索......


  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanfen1312 2010-05-03 13:20

    Try this:

    sed -r $'s/(\$LD = )(\'.*\')(.*)/\\1_(\\2)\\3/' filename


    $ echo "\$LD = 'Some String';" | sed -r $'s/(\$LD = )(\'.*\')(.*)/\\1_(\\2)\\3/'
    $LD = _('Some String');


    This will look for and change both variables, the -i will make the change in-place:

    sed -i -r $'s/(\$(LD|Another) = )(\'.*\')(.*)/\\1_(\\3)\\4/'

    You can list more variable names separated by pipe characters.

    Your grep command needs single quotes instead of backticks and a -E to use extended regexes. It also needs a filespec glob. The regex as you have basically says "Does this file have any variable definitions?" It says to look for any variable that:

    • starts at the beginning of the line with no whitespace before it
    • has zero or more array subscripts consisting of zero or more digits (which would include a null subscript, thus an array append)
    • ignore any associative array assignments ($array["key"]=value)
    • the line must end in a semicolon
    • I'm not sure what the ? is intended to do

    This fails if the variable assignment:

    • occurs after some whitespace
    • uses an alpha key or a variable as a key
    • occurs on a line with other statements
    • has any trailing whitespace
    • possibly others

    You might need to make your regex more robust or simpler or just assume that any PHP file will have a variable assignment and let sed look for and change just the variables of interest.

    In order for your grep to have files to process, you need to specify which files to look at:

    grep -E -i -R 'your regex' * | sed ...

    Or, if you let sed do it:

    find . -name "*.php" | sed ...

    Also, a tool called ack is better than grep for finding stuff in code files.

    In any case, especially if you use the in-place option, I strongly recommend test runs (and backups).

    解决 无用
    打赏 举报

相关推荐 更多相似问题