代码之家  ›  专栏  ›  技术社区  ›  Barry

Bash:转换为小写,但保留每个单词第一个字母的大小写

  •  1
  • Barry  · 技术社区  · 3 年前

    我反复搜索,但找不到这个特定场景的答案。我希望能够将字符串转换为小写,同时还保留任何现有的有标题的词。

    例如:

    Hello, this is a Titled woRd aND ThIs one is UPPERCASED.
    

    Hello, this is a Titled word and This one is Uppercased.
    

    每个字母都将小写,除了每个单词的第一个字母将保留大小写。我很熟悉改变案例的常见形式,但不是这么具体。不要和标题混淆,因为这不是我在这里要问的。非常感谢您的帮助。

    0 回复  |  直到 3 年前
        1
  •  2
  •   Raman Sailopal    3 年前

    使用GNU awk:

    awk '{ for (i=1;i<=NF;i++) { printf "%s",substr($i,1,1);for(j=2;j<=length($i);j++) { printf "%s",tolower(substr($i,j,1))} printf "%s"," " } }' <<< "Hello, this is a Titled woRd aND ThIs one is UPPERCASED."
    

    awk '{ 
           for (i=1;i<=NF;i++) {                           # Loop on each word
              printf "%s",substr($i,1,1);                  # Print the first letter in the word
              for(j=2;j<=length($i);j++) {  
                printf "%s",tolower(substr($i,j,1))        # Loop on the rest of the letters in the word and print in lower case
              }  
           printf "%s"," "                                 # Print a space
           } 
         }' <<< "Hello, this is a Titled woRd aND ThIs one is UPPERCASED."
    

    使用bash:

    for var in $(echo "Hello, this is a Titled woRd aND ThIs one is UPPERCASED.");
    do 
       printf "%s" ${var:0:1};             # Print the first letter of the word
       var1=${var:1};                      # Read the rest of the word into var1
       printf "%s " "${var1,,[$var1]}";    # Convert vars into lowercase and print
    done
    
        2
  •  3
  •   Thomas    3 年前

    不知道你是否需要一个纯净的 bash 解决方案,但使用一些常用的实用程序使生活更轻松。

    awk :

    $ echo 'Hello, this is a Titled woRd aND ThIs one is UPPERCASED.' | \
        awk '{for(i=1;i<=NF;i++){$i=substr($i,1,1)tolower(substr($i,2))}}1'
    Hello, this is a Titled word and This one is Uppercased.
    

    $i )该字段的第一个字母,后跟该字段其余部分的降格副本。

    sed (便携性较差,但可读性可能更高):

    $ echo 'Hello, this is a Titled woRd aND ThIs one is UPPERCASED.' | \
        sed -r 's/\b(\w)(\w*)/\1\L\2/g'
    Hello, this is a Titled word and This one is Uppercased.
    

    \b )后跟一个字母(单词字符, \w )然后是零个或更多的字母( \w* \1 ),后跟小写版本( \L \2 ).