bash 如何在bash中将每一行的第一个字母大写?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43705853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to capitalize first letter of each line in bash?
提问by morkan
I'm looking for a command that capitalizes the first letter of each line in bash.
我正在寻找一个将 bash 中每一行的第一个字母大写的命令。
Actually I used this command:
实际上我使用了这个命令:
sed 's/^\(.\)/\U/'
But I need to use another command instead of "\U". .
但我需要使用另一个命令而不是“\U”。.
回答by choroba
Why do you need to use something else than \U
?
为什么你需要使用其他东西\U
?
You can use \u
which only capitalizes one letter:
您可以使用\u
which 只大写一个字母:
sed 's/./\u&/'
Or, use parameter expansion:
或者,使用参数扩展:
while read line ; do echo "${line^}" ; done
回答by Walter A
Split your file in first character/rest of line, upper the first and paste te columns together.
将文件拆分为第一个字符/行的其余部分,将第一列放在上面并将 te 列粘贴在一起。
paste -d "" <(cut -c1 inputfile| tr '[:lower:]' '[:upper:]') <(cut -c2- inputfile)
EDIT:
When you want to parse input from a stream (like mycommand | myscript.sh
), my original solution will cause problems. My solution wants to parse the input twice. When you can wait until the input process is finished, you can redirect the output to a tmp file
编辑:
当您想解析来自流的输入(如mycommand | myscript.sh
)时,我的原始解决方案会导致问题。我的解决方案想要解析输入两次。当您可以等到输入过程完成时,您可以将输出重定向到一个 tmp 文件
tmpfile=/tmp/myscript.wrk
# read input with cat
cat > ${tmpfile}
paste -d "" <(cut -c1 ${tmpfile}| tr '[:lower:]' '[:upper:]') <(cut -c2- ${tmpfile})
rm -f ${tmpfile} 2>/dev/null
You can try the same on a commandline. Withot the sleep, the second cut will find an empty file. The sleep of 1 second will fail when the original command runs for more than a second
您可以在命令行上尝试相同的操作。没有睡眠,第二次剪辑会找到一个空文件。原命令运行时间超过1秒,休眠1秒就会失败
mycommand | tee /tmp/dont_do_this |
cut -c1 | tr '[:lower:]' '[:upper:]' |
paste -d "" - <(sleep 1;cut -c2- /tmp/dont_do_this)
Reviewing the above solutions will lead to the conclusion that you should use a solution like @choroba posted. When the instructor says you should use [:lower:]
is like asking if you want to have coffee and add that you should drink it through your nose: possible but not nice.
When you really like to do this, try the next solution:
查看上述解决方案将得出结论,您应该使用像@choroba 发布的解决方案。当教练说您应该使用时[:lower:]
,就像询问您是否想喝咖啡并补充说您应该通过鼻子喝:可能但不好。
当您真的喜欢这样做时,请尝试下一个解决方案:
mycommand | while read -r line; do
printf "%s%s\n" $(tr '[:lower:]' '[:upper:]' <<< "${line:0:1}") "${line:1}"
done
回答by hill flame
this is a simple way that work fine: sed -e 's/^./\U&/' yourfile
这是一种工作正常的简单方法: sed -e 's/^./\U&/' yourfile