如何:在 Bash 中按照标题大小写规则转换文本 [英] How To: Convert Text Following Title Case Rules in Bash

查看:22
本文介绍了如何:在 Bash 中按照标题大小写规则转换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在遵循规则的同时将字符串转换为标题大小写,而不只是简单地将单词的每个首字母大写?

How to convert string to title case while following rules, not just simply capitalizing every first letter of the word?

示例规则:

  • 将所有单词大写,但以下内容除外:
  • 小写所有冠词(a、the)、介词(to、at、in、with)和并列连词(and、but、or)
  • 将标题中的第一个和最后一个单词大写,与词性无关

有什么简单的方法可以在 bash 中做到这一点?One-liners 表示赞赏.

Any easy way to do this in bash? One-liners appreciated.

(作为附加说明,这将用于 parcellite 操作.)

(And just as an additional note, this is to be used in parcellite actions.)

推荐答案

$ cat titles.txt
purple haze
Somebody To Love
fire on the mountain
THE SONG REMAINS THE SAME
Watch the NorthWind rise
eight miles high
just dropped in
strawberry letter 23

$ cat cap.awk
BEGIN { split("a the to at in on with and but or", w)
        for (i in w) nocap[w[i]] }

function cap(word) {
    return toupper(substr(word,1,1)) tolower(substr(word,2))
}

{
  for (i=1; i<=NF; ++i) {
      printf "%s%s", (i==1||i==NF||!(tolower($i) in nocap)?cap($i):tolower($i)),
                     (i==NF?"
":" ")
  }
}

$ awk -f cap.awk titles.txt
Purple Haze
Somebody to Love
Fire on the Mountain
The Song Remains the Same
Watch the Northwind Rise
Eight Miles High
Just Dropped In
Strawberry Letter 23

编辑(作为一行):

$ echo "the sun also rises" | awk 'BEGIN{split("a the to at in on with and but or",w); for(i in w)nocap[w[i]]}function cap(word){return toupper(substr(word,1,1)) tolower(substr(word,2))}{for(i=1;i<=NF;++i){printf "%s%s",(i==1||i==NF||!(tolower($i) in nocap)?cap($i):tolower($i)),(i==NF?"
":" ")}}'
The Sun Also Rises

这篇关于如何:在 Bash 中按照标题大小写规则转换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆