【发布时间】:2014-03-24 23:00:17
【问题描述】:
我知道我可以用 awk 做到这一点,但我想知道如何用 sed 做到这一点。 我知道如何将每行的第一个字母转换为大写:
sed 's/^\(.\)/\U\1/' input > output
但我想将前 2 个单词的第一个字母转换为大写。
输入文件:
这是我的文件
输出文件:
这是我的文件
我认为这一定可以用 sed 实现,但我想不通。
【问题讨论】:
我知道我可以用 awk 做到这一点,但我想知道如何用 sed 做到这一点。 我知道如何将每行的第一个字母转换为大写:
sed 's/^\(.\)/\U\1/' input > output
但我想将前 2 个单词的第一个字母转换为大写。
输入文件:
这是我的文件
输出文件:
这是我的文件
我认为这一定可以用 sed 实现,但我想不通。
【问题讨论】:
你也许可以使用-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
【讨论】:
sed 's/\<./\U&/1; s/\<./\U&/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:
\UTurn 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
【讨论】:
我知道它没有要求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
【讨论】:
只是为了好玩,perl
perl -ane '@F[0,1] = map {ucfirst} @F[0,1]; print "@F"'
【讨论】: