制作一个将句子转换为首字母大写的脚本?

Making a script that transforms sentences to title case?

我有一个命令可以用来将句子转换为首字母大写。必须将此命令从文本文件中复制出来,然后将其粘贴到终端,然后再粘贴我要转换的句子,效率很低。命令为:

echo "my text" | sed 's/.*/\L&/; s/[a-z]*/\u&/g'

如何将其转换为脚本以便我可以从终端调用如下内容:

TitleCaseConverter "my text"

是否可以创建这样的脚本?是否可以让它在任何文件夹位置工作?

如何将它从当前 shell

包装到 .bashrc.bash_profilesource 中的函数中?
TitleCaseConverter() {
    sed 's/.*/\L&/; s/[a-z]*/\u&/g' <<<""    
}

或)如果你希望它完美地避免输入参数中的任何形式的尾随新行,请执行

printf "%s" "" | sed 's/.*/\L&/; s/[a-z]*/\u&/g'

现在您可以从命令行 source 文件一次以使该功能可用,请执行

source ~/.bash_profile

现在可以直接在命令行中使用了

str="my text"
newstr="$(TitleCaseConverter "$str")"
printf "%s\n" "$newstr"
My Text

还有你的问题,

How can I convert this to a script so I can just call something like the following from the terminal

将函数添加到启动文件之一可以解决这个问题,建议将其添加到 .bash_profile

TitleCaseConverter "this is Whosebug"
This Is Whosebug

更新:

OP 试图用函数调用返回的名称创建一个目录,如下所示

mkdir "$(TitleCaseConverter "this is Whosebug")"

这里的关键再次是双引号替换命令,以避免被 shell 分词。

由于 bash 参数扩展 包括 case modification,因此不需要 sed。只是一个简短的功能:

 tc() { set ${*,,} ; echo ${*^} ; }

测试(不要使用引号,因为标题通常不会超过一个句子,所以应该无关紧要):

tc FOO bar

输出:

Foo Bar

避免将某些连词、冠词等大写的精美版本:

ftc() { set ${*,,} ; set ${*^} ; echo -n " " ; shift 1 ; \
        for f in ${*} ; do \
            case $f in  A|The|Is|Of|And|Or|But|About|To|In|By) \
                    echo -n "${f,,} " ;; \
                 *) echo -n "$f " ;; \
            esac ; \
        done ; echo ; }

测试:

ftc the last of the mohicans

输出:

The Last of the Mohicans 

我没有评论权限,但对 ManUnitedBloke 的回答略有改进,这将处理诸如“不要”和“谁”之类的缩写。

echo "my text" | sed 's/.*/\L&/; s/[a-z']*/\u&/g'