Capitalizing the First Letter of Each Line in Bash Script Output
In this note I want to look at ways to output lists in bash while capitalizing the first letter/character.
I’ll use an example of printing the installed versions of Postfix and Dovecot on CentOS:
Example 1: for loops.
This example creates a new variable $newf made up of two parts. In the first part, tr converts the segment from character 0 through the first character from lowercase to uppercase.
for f in $(rpm -qa |grep "dovecot\|postfix" |sed 's/-/\ v\./g' |awk '{print $1"_"$2}');
do
newf=$(tr '[:lower:]' '[:upper:]' <<< ${f:0:1})${f:1};
echo $newf |sed 's/_v/ v/g';
done
A slightly modified version:
for f in $(rpm -qa |grep "dovecot\|postfix");
do
tf=$(echo $f |sed 's/-/\ v\./g' |awk '{print $1" "$2}')
newf=$(tr '[:lower:]' '[:upper:]' <<< ${tf:0:1})${tf:1};
echo $newf |sed 's/_v/ v/g';
done
Example 2: while loop.
Same logic as in the first example, just a different loop.
while read -r line;
do
f=$(printf '%s\n' "$line");
newf=$(tr '[:lower:]' '[:upper:]' <<< ${f:0:1})${f:1}; echo $newf;
done <<< "$(rpm -qa |grep "dovecot\|postfix" |sed 's/-/\ v\./g'|awk '{print $1" "$2}')"