Search code examples
stringshellfishcapitalizationcapitalize

How to capitalize string in fish shell?


I got the following text:

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

That I want to capitalize, i.e. uppercase first letter of every word.

Expected result

Lorem Ipsum Dolor Sit Amet, Consectetur Adipisicing Elit.

Bash equivalent

Using bash, I was using a parameter expansion:

function to-lower() { echo "$@" |tr '[:upper:]' '[:lower:]' ; }

function capitalize() {
    input="$(to-lower "$@")"
    for i in $input; do
        cap=$(echo -n "${i:0:1}" | tr "[:lower:]" "[:upper:]")
        echo -n "${cap}${i:1} "
    done
    echo
}

Question

How do I do that in a fish-way?


Solution

  • Fish currently doesn't have any tools to do this (in a release), so assuming you have GNU sed you can do this:

    function capitalize
        echo $argv | sed 's/[^ _-]*/\u&/g'
    end
    

    There are also a variety of other tools, you can also do it with e.g. python or by calling bash from fish, the point is that there is no way to either extract a substring or replace a character with fish builtins.

    In the next fish release, you'll be able to use string sub -l 1 $i to extract the first character.