dongsuo0517 2010-05-03 11:15
浏览 32
已采纳

从另一个文件替换php中的字符串

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 ...

  • 写回答

1条回答 默认 最新

  • duanfen1312 2010-05-03 13:20
    关注

    Try this:

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

    Example:

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

    Edit:

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用