【问题标题】:Convert first letters of the first 2 words to Upper using sed使用 sed 将前 2 个单词的首字母转换为大写
【发布时间】:2014-03-24 23:00:17
【问题描述】:

我知道我可以用 awk 做到这一点,但我想知道如何用 sed 做到这一点。 我知道如何将每行的第一个字母转换为大写:

sed  's/^\(.\)/\U\1/' input > output

但我想将前 2 个单词的第一个字母转换为大写。

输入文件:

这是我的文件

输出文件:

这是我的文件

我认为这一定可以用 sed 实现,但我想不通。

【问题讨论】:

    标签: regex sed


    【解决方案1】:

    你也许可以使用-e 做两个块:

    $ echo "this is my file" | sed -e 's/^\(.\)/\U\1/' -e 's/ \(.\)/ \U\1/'
    This Is my file                    ^^^^^^^^^^^^^^      ^^^^^^^^^^^^^^^
                                       first word          second word
    

    请注意,您可以使用-r 参数使线条更清晰,该参数允许使用简单的(XXX) 而不是\(XXX\) 进行捕捉:

    $ echo "this is my file" | sed -re 's/^(.)/\U\1/' -e 's/ (.)/ \U\1/' 
    This Is my file
    

    【讨论】:

    • 你真的简化了我的生活:)
    • 如果你使用单词锚和 GNU sed:sed 's/\<./\U&/1; s/\<./\U&/2'
    【解决方案2】:

    使用捕获组和\U\E 来关闭大写:

    sed 's/^\(.\)\([^ ]* \)\(.\)/\U\1\E\2\U\3/' input > output
    

    sed -r 's/^(.)([^ ]* )(.)/\U\1\E\2\U\3/' input > output
    

    引用the manual:

    \U

    Turn the replacement to uppercase until a \L or \E is found
    

    举个例子:

    $ echo 'this is my life' | sed 's/^\(.\)\([^ ]* \)\(.\)/\U\1\E\2\U\3/'
    This Is my life
    

    【讨论】:

      【解决方案3】:

      我知道它没有要求awk,但如果其他人有兴趣,请发布一个通用解决方案。

      echo "this is my file" | awk '{for (i=1;i<=2;i++) sub(".",substr(toupper($i),1,1),$i)}1'
      This Is my file
      

      它可以很容易地变成n个单词,如果你想改变一个单词的两个首字母:

      echo "this is my file" | awk '{for (i=1;i<=2;i++) sub("..",substr(toupper($i),1,2),$i)}1'
      THis IS my file
      

      【讨论】:

        【解决方案4】:

        只是为了好玩,perl

        perl -ane '@F[0,1] = map {ucfirst} @F[0,1]; print "@F"'
        

        【讨论】:

          猜你喜欢
          • 2010-12-05
          • 2014-11-15
          • 2017-05-28
          • 1970-01-01
          • 2015-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多