【问题标题】:Converting text to title case, except for certain words like 'the', 'a', 'of', etc.? [duplicate]将文本转换为标题大小写,除了某些单词,如“the”、“a”、“of”等? [复制]
【发布时间】:2017-03-25 14:36:49
【问题描述】:

我的 bashrc 文件中有命令脚本,一个以字符串为标题,另一个使用以标题为大小写的字符串创建目录。命令是:

tc() {
    sed 's/.*/\L&/; s/[a-z]*/\u&/g' <<<"$1"    
}

tcdir() {
    mkdir "$(tc "$1")";
}

我怎样才能修改 tc() 命令,使其不使用“the”、“a”、“of”、“in”、“for”等单词的标题,除非它们是字符串中的第一个单词?例如:

the name of the website is stackoverflow

转化为

The Name Of The Website Is Stackoverflow

理想情况下我希望它转变为

The Name of the Website is Stackoverflow

【问题讨论】:

  • 通过管道传送到sed -E 's/ (The|A|Of|I[sn]|For)\b/\L&amp;/g'...您需要手动指定所有单词...
  • @Sundeep 好的,我尝试使用 sed -E 's/ (The|A|Of|I[sn]|For)\b/\L&/g' | sed 's/.*/\L&/; s/[a-z]*/\u&/g'
  • 订单应该是echo "$1" | sed 's/.*/\L&amp;/; s/[a-z]*/\u&amp;/g' | sed -E 's/ (The|A|Of|I[sn]|For)\b/\L&amp;/g'
  • 纯 bash(不调用外部程序):codegolf.stackexchange.com/a/113666/29143 :)

标签: bash shell sed


【解决方案1】:

bash,(根据需要给case加词):

tc() { set ${*,,} ; set ${*^} ; c="$1 " ; shift 1 ;
       for f in ${*} ; do
           case $f in  A|The|Is|Of|For|And|Or|But|About) c+="${f,,} " ;;
                                                      *) c+="$f " ;;      
           esac ;
       done ; echo "$c"; }

注意:shift 1 允许第一个单词保留在标题中。

测试:

tc the last of the mohicans

输出:

The Last of the Mohicans 

【讨论】:

    【解决方案2】:

    还有一个纯粹的 bash 方面:

    tc()
    {
      excluded_words=(a the if is of and for or but about)
    
      IFS='|'
      regex="^("${excluded_words[*]}")$"
      unset IFS  
    
      set ${*,,}
    
      out=${1^}
    
      shift
    
      for word
      do
        [[ "$word" =~ $regex ]] || word=${word^}
    
        out+=" $word"
      done
    
      echo "$out"
    }
    

    这里的好处是您可以将不需要的每个单词添加到 exclude_words 数组中。您还可以使用外部文件填充数组

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-05-24
      • 2023-02-22
      • 2012-11-27
      • 1970-01-01
      • 2020-04-28
      • 2012-07-25
      • 1970-01-01
      • 2018-08-06
      相关资源
      最近更新 更多