【问题标题】:extract and replace a token in shell script提取和替换 shell 脚本中的令牌
【发布时间】:2011-01-13 07:47:15
【问题描述】:

在源代码文件中,我需要更改所有实例,例如

foo_bar('param')

成为

booch['param']=$param

这里,param 是一个令牌,它可以变化。它可以是任何东西。

即在文件中,

所有的

foo_bar('xxx')

必须成为

booch['xxx']=$xxx

和,

所有的

foo_bar('yyy')

必须成为

booch['yyy']=$yyy

等等。我正在尝试通过编写 shell 脚本并使用 sed 来做到这一点。但无法弄清楚如何做到这一点。希望我的查询是可以理解的。谢谢

【问题讨论】:

    标签: regex shell sed token


    【解决方案1】:
    sed "s/foo_bar('\([^']*\)')/booch['\1']=$\1/g" infile > outfile
    

    测试

    $ echo "foo_bar('xxx')" | sed "s/foo_bar('\(.*\)')/booch['\1']=$\1/"
    booch['xxx']=$xxx
    

    【讨论】:

      【解决方案2】:

      基本一样,用perl

      cat yourfile.txt | perl -pe "s/(foo_bar)\(\s*('(\w*)')\s*\)/booch\[\$2\]=\\$\$3/" > youralteredfile.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 2018-06-04
        • 2012-06-07
        • 2018-07-09
        • 1970-01-01
        • 2016-03-18
        • 2020-04-29
        相关资源
        最近更新 更多