如何:在Bash中转换标题案例规则之后的文本

Maj*_*jal -4 string bash awk sed tr

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

示例规则:

  • 将所有单词大写,但以下情况除外:
  • 小写所有文章(a,the),介词(to,at,in,with)和协调连词(和,但是,或)
  • 无论词性如何,都可以将标题中的第一个和最后一个词大写

在bash中执行此操作的任何简单方法?单行赞赏.

(正如另外一点,这是用于parcellite行动.)

jas*_*jas 7

$ 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?"\n":" ")
  }
}

$ 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
Run Code Online (Sandbox Code Playgroud)

编辑(作为一个班轮):

$ 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?"\n":" ")}}'
The Sun Also Rises
Run Code Online (Sandbox Code Playgroud)