bashshell

Making a script that transforms sentences to title case?


I have a command that I use to transform sentences to title case. It is inefficient to have to copy this command out of a text file, and then paste it into the terminal before then also pasting in the sentence I want converted. The command is:

echo "my text" | sed 's/.*/\L&/; s/[a-z]*/\u&/g'

How can I convert this to a script so I can just call something like the following from the terminal:

TitleCaseConverter "my text"

Is it possible to create such a script? Is it possible to make it work from any folder location?


Solution

  • How about just wrapping it into a function in .bashrc or .bash_profile and source it from the current shell

    TitleCaseConverter() {
        sed 's/.*/\L&/; s/[a-z]*/\u&/g' <<<"$1"    
    }
    

    or) if you want it pitch-perfect to avoid any sorts of trailing new lines from the input arguments do

    printf "%s" "$1" | sed 's/.*/\L&/; s/[a-z]*/\u&/g'
    

    Now you can source the file once from the command line to make the function available, do

    source ~/.bash_profile
    

    Now you can use it in the command line directly as

    str="my text"
    newstr="$(TitleCaseConverter "$str")"
    printf "%s\n" "$newstr"
    My Text
    

    Also to your question,

    How can I convert this to a script so I can just call something like the following from the terminal

    Adding the function to one of the start-up files takes care of that, recommend adding it to .bash_profile more though.

    TitleCaseConverter "this is stackoverflow"
    This Is Stackoverflow
    

    Update:

    OP was trying to create a directory with the name returned from the function call, something like below

    mkdir "$(TitleCaseConverter "this is stackoverflow")"
    

    The key again here is to double-quote the command-substitution to avoid undergoing word-splitting by shell.