Uppercasing First Letter of Words Using SED

前端 未结 9 1334
误落风尘
误落风尘 2020-12-07 20:49

How do you replace the first letter of a word into Capital letter, e.g.

Trouble me
Gold rush brides

into

Trouble Me
Gold R         


        
相关标签:
9条回答
  • 2020-12-07 21:52

    Using sed with tr:

    name="athens"
    echo $name | sed -r "s/^[[:alpha:]]/$(echo ${name:0:1} | tr [[:lower:]] [[:upper:]])/"
    
    0 讨论(0)
  • 2020-12-07 21:54

    I had apostrophes so, working off the first solution...

    mike@mike-laptop3:~$ echo "BEST WESTERN PLUS BOB's INN" | tr "[A-Z]" "[a-z]" | sed -e "s/\b\(.\)/\u\1/g"
    

    Best Western Plus Bob'S Inn

    mike@mike-laptop3:~$ echo "BEST WESTERN PLUS BOB's INN" | tr "[A-Z]" "[a-z]" | sed "s/\( \|^\)\(.\)/\1\u\2/g"
    

    Best Western Plus Bob's Inn

    0 讨论(0)
  • 2020-12-07 21:56

    I know you said sed, but for shell scripting one of the easiest and more flexible for me was using Python which is available in most systems:

    $ echo "HELLO WORLD" | python3 -c "import sys; print(sys.stdin.read().title())"
    Hello World
    

    For example:

    $ lorem | python3 -c "import sys; print(sys.stdin.read().title())"
    Officia Est Omnis Quia. Nihil Et Voluptatem Dolor Blanditiis Sit Harum. Dolore Minima Suscipit Quaerat. Soluta Autem Explicabo Saepe. Recusandae Molestias Et Et Est Impedit Consequuntur. Voluptatum Architecto Enim Nostrum Ut Corrupti Nobis.
    

    You can also use things like strip() to remove spaces, or capitalize():

    $ echo "  This iS mY USER ${USER}   " | python3 -c "import sys; print(sys.stdin.read().strip().lower().capitalize())"
    This is my user jenkins
    
    0 讨论(0)
提交回复
热议问题