perl 或 sed:用某种关系替换单词

perl 或 sed:用某种关系替换单词

我使用TeaCode,TeaCode有一个TeaCode语言,并且在模板文本中有以下定义:

md5 converts text into MD5 hash value
uppercase makes all the letters UPPERCASE
capitalize Converts First Letter Of Each Word To Uppercase
camelcase converts text to camelCase
snakecase converts text to snake_case
dashcase converts text to dash-case
lowercase makes all the letters lowercase
sha1 converts text into SHA1 hash value
pascalcase converts text to PascalCase
remove_spaces removesallthespaces
lcfirst makes the first letter lowercase
ucfirst makes the last letter uppercase

例如:

For pattern vc ${name:word}, the template is:

class ${name.capitalize}ViewController: NSViewController {

    #
}

这意味着如果用户输入vc main,输出代码将是:

class MainViewController: NSViewController {

    |
}

所以我想要的结果是:

输入:要替换为模板变量的单词。

输出:模板文本已被替换。

示例1:

输入文本:

class MainViewController: NSViewController {

    // this is main text
    // this is maintain
    // this is Maintain
    // this is Main text
}

输入:

main

输出文本:

class ${main.capitalize}Controller: NSViewController {

    // this is ${main} text
    // this is maintain
    // this is Maintain
    // this is ${main.capitalize} text
}

注意:只能将main替​​换为单词,例如maintain,main不是单词。

答案1

如果我理解正确的话,你可以尝试以下方法sed

例子:

class FooViewController: NSViewController {

    // this is foo text
    // this is foobar
    // this is Foobar
    // this is Foo text
    // foo
    // Foo
    // BarFoo
    // barfoo
}


word="foo"

命令:

sed -e "s/^class .*Controller/class \${$word.capitalize}Controller/" -e "s/\( \|$\)$word\( \|$\)/\1\${$word}\2/" -e "s/\( \|^\)${word^}\( \|$\)/\1\${$word.capitalize}\2/" file

输出:

class ${foo.capitalize}Controller {

    // this is ${foo} text
    // this is foobar
    // this is Foobar
    // this is ${foo.capitalize} text
    // ${foo}
    // ${foo.capitalize}
    // BarFoo
    // barfoo
}

相关内容