Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

linux - Troubleshooting bash script to capitalize first letter in every word

I have a text file in the following format:

jAY
JAY
JaY

eVAns
Evans
Evans

What I'm trying to do is convert everything to lowercase and then capitalize the first letter of every word. For my script, however, I'm not printing out the correct information.

#!/bin/bash

FILE=names.txt

echo "#################################"
k=1
while read line;do

VAR=$line
VARCAP=$( echo "${VAR}" | tr '[A-Z]' '[a-z]')";
VARCAP1=$( echo "${VARCAP}" | awk '{for(i=1;i<=NF;i++)sub(/./,toupper(substr($i,1,1)),$i)}1')

echo "Line # $k: $VARCAP1"
((k++))
done < $FILE
echo "Total number of lines in file: $k"

Everything was working until I added the line to convert all the letters to lowercase - so that is where my problem lies. This is the first bash script I've ever written, so to say I'm green is an understatement.

Any assistance would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I said in a comment of the OP, you can use (in Bash≥4) the following:

${var,,}
${var^}

to respectively have the expansion of var in lowercase and var in lowercase with first letter capitalize. The good news is that this also works on each field of an array.

Note. It is not clear from you question whether you need to apply this on each word of a line, or on each line. The following addresses the problem of each word of a line. Please refer to Steven Penny's answer to process only each line.

Here you go, in a much better style!

#!/bin/bash

file=names.txt
echo "#################################"
k=1
while read -r -a line_ary;do
    lc_ary=( "${line_ary[@],,}" )
    echo "Line # $k: ${lc_ary[@]^}"
    ((++k))
done < "$file"
echo "Total number of lines in file: $k"

First we read each line as an array line_ary (each field is a word).

The part lc_ary=( "${line_ary[@],,}" ) converts each field of line_ary to all lowercase and stores the resulting array into lc_ary.

We now only need to apply ^ to the array lc_ary and echo it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...