Uppercasing First Letter of Words Using SED

前端 未结 9 1333
误落风尘
误落风尘 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:37

    Using bash (without sed, so a little off topic):

    msg="this is a message"
    for word in $msg
    do
       echo -n ${word^} ""
    done
    
    This Is A Message
    
    0 讨论(0)
  • 2020-12-07 21:42

    Use the following sed command for capitalizing the first letter of the each word.

    echo -e "Trouble me \nGold rush brides" | sed -r 's/\<./\U&/g'
    

    output

    Trouble Me
    Gold Rush Brides
    

    The -r switch tells sed to use extended regular expressions. The instructions to sed then tell it to "search and replace" (the s at the beginning) the pattern \<. with the pattern \U& globally, i.e. all instances in every line (that's the g modifier at the end). The pattern we're searching for is \<. which is looking for a word boundary (\<) followed by any character (.). The replacement pattern is \U&, where \U instructs sed to make the following text uppercase and & is a synonym for \0, which refers to "everything that was matched". In this case, "everything that was matched" is just what the . matched, as word boundaries are not included in the matches (instead, they are anchors). What . matched is just one character, so this is what is upper cased.

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

    Proposed sed solutions until now will only work if the original text is in lowercase. Although one could use tr '[[:upper:]]' '[[:lower:]]' to normalize the input to lowercase, it may be convenient to have an all-in-one sed solution :

    sed 's/\w\+/\L\u&/g'
    

    This will match words (\w means word character, and \+ at least one and until the next non-word character), and lowercase until the end (\L) but uppercase the next (i.e. first) character (\u) on each (g) matched expression (&).

    [Credits]

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

    This line should do it:

    sed -e "s/\b\(.\)/\u\1/g"
    
    0 讨论(0)
  • 2020-12-07 21:50

    Another shorter version with sed:

    sed -e "s/\b./\u\0/g"
    
    0 讨论(0)
  • 2020-12-07 21:52

    Using awk:

    awk '{for(i=1;i<=NF;i++){ $i=toupper(substr($i,1,1)) substr($i,2) }}1' file
    

    The output would be:

    Trouble Me
    Gold Rush Brides
    
    0 讨论(0)
提交回复
热议问题