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.
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.
declare -c rw
mapfile -t rw < names.txt
printf '%s\n' "${rw[@]}"
Result
Jay
Jay
Jay
Evans
Evans
Evans
Converting string to lower case in Bash shell scripting