Question

I need help with capitalizing the first letter of the first word in sentences from an input file input.txt:

this is my first sentence. and this is the second sentence. that one is the third.

I want to make the output look like this in an output file output.txt:

This is my first sentence. And this is the second sentence. That one is the third.

Was it helpful?

Solution 2

bash version 4 way:

#!/usr/local/bin/bash

while IFS="." read -r -a line ; do
    for ((i=0; i<${#line[@]}; i++)) do
        if [[ $i > 0 ]]; then
            temp=$(echo ${line[$i]/ /})
            echo -n "${temp^}. "
        else
            echo -n "${line[$i]^}. "
        fi
    done
    echo
done < file

OTHER TIPS

Try this:

sed -r "s/(^|\.\s+)./\U&/g" <input.txt >output.txt

What about awk way?

$ awk -F"\. " '{OFS=". "}{for (i=0;i<=NF;i++) {sub(".", substr(toupper($i), 1,1) , $i)}} {print}' output.txt 
This is my first sentence. And this is the second sentence. That one is the third.
  • -F"\. " sets the field delimiter to . (dot + space).
  • {OFS=". "} sets the output field delimiter to . (dot + space).
  • '{for (i=0;i<=NF;i++) {sub(".", substr(toupper($i), 1,1) , $i)}} loops through each field capitalizing the first word of them. As first field is this is my first sentence, it just capitalizes this.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top