その他
    ホーム技術発信DoRubymacのbashスクリプト上で文字列のcamelizeやunderscoreをしようとしたらperlに頼るのが楽だったこと

    macのbashスクリプト上で文字列のcamelizeやunderscoreをしようとしたらperlに頼るのが楽だったこと

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    ruby on rails ではコントローラ名やそこで扱われるモデル名やインスタンス変数名の変換を行いたいときなど、文字列にcamelizeメソッドやunderscoreメソッドがある。 同様のことシェルスクリプト上で行おうとして探してみたところ、macのbash上ではperlを呼び出すのが楽だった。

    bashでcamelizeやunderscore

    rails上での String#camelize, String#underscore の例

    str = 'happy_birthday_to_you!'
    Str = str.camelize
     => "HappyBirthdayToYou!"
    Str.underscore
     => "happy_birthday_to_you!" 
    
    • 環境 ruby 2.5.0 rails 5.0.6

    bashでやってみる

    まずはcamelize

    sedを使うとできるらしい

    str=happy_birthday_to_you!
    echo $str | sed -re "s/(^|_)(.)/\U\2/g"
    HappyBirthdayToYou!
    

    sedで正規表現を使うことでできる。(redhat, debian)

    ところがmac(Darwin)のsedではエラーになる。

    str=happy_birthday_to_you!
    echo $str | sed -re "s/(^|_)(.)/\U\2/g"
    sed: illegal option -- r
    usage: sed script [-Ealn] [-i extension] [file ...]
           sed [-Ealn] [-i extension] [-e script] ... [-f script_file] ... [file ...]
    

    perlを使えばmacでも動く

    str=happy_birthday_to_you!
    echo $str | perl -pe ‘s/(|)./uc($&)/ge;s///g’

    つづいてunderscore

    sed使用版

    Str=HappyBirthdayToYou!
    echo $Str | sed -r -e 's/^([A-Z])/\L\1\E/' -e 's/([A-Z])/_\L\1\E/g'
    happy_birthday_to_you!
    

    macだとやはり同じsedのエラー

    perl使用版

    Str=HappyBirthdayToYou!
    echo $Str | perl -pe 's/(^[A-Z])/lc($&)/ge;s/([A-Z])/_$&/g;s/([A-Z])/lc($&)/ge'
    happy_birthday_to_you!
    

    できたこととする。