How to capitalize first letter of each line in bash? [duplicate]

和自甴很熟 提交于 2019-12-05 08:14:50

问题


I'm looking for a command that capitalizes the first letter of each line in bash.

Actually I used this command:

sed 's/^\(.\)/\U\1/'

But I need to use another command instead of "\U". .


回答1:


Why do you need to use something else than \U?

You can use \u which only capitalizes one letter:

sed 's/./\u&/'

Or, use parameter expansion:

while read line ; do echo "${line^}" ; done



回答2:


Split your file in first character/rest of line, upper the first and paste te columns together.

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

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

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:

mycommand | while read -r line; do
   printf "%s%s\n" $(tr '[:lower:]' '[:upper:]' <<< "${line:0:1}") "${line:1}"
done



回答3:


this is a simple way that work fine: sed -e 's/^./\U&/' yourfile



来源:https://stackoverflow.com/questions/43705853/how-to-capitalize-first-letter-of-each-line-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!