Saturday, May 4, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 10987  / 1 Year ago, mon, january 9, 2023, 6:03:15

I am trying to capitalize each first letter of the first word in each sentence from a txt file called input.txt and I want this input file to be a argument of the shell script



 ./script.sh input.txt


sample input file:



i am Andrew. you are Jhon. here we are, forever.


result file:



I am Andrew. You are Jhon. Here we are, forever.


A special case. What if our text is (related to @RaduRadeanu answer)



i am andrew. you
are jhon. here we are
forever


the result would be:



I am andrew. You
Are jhon. Here we are
Forever.


So it convert to uppercase each first word of each sentence and also each first word of new line. How do we skip over uppercase first word of new line?



So the correct result must be:



I am andrew. You
are jhon. Here we are
forever.


What if the sentence closes in "?" or "!" ???


More From » scripts

 Answers
6

sed command is very powerful to edit files from shell scripts. With its help you can edit however you want a text file. These being said, the following script can do what you wish:



#!/bin/bash

#check if a file is given as argument
if [ $# -ne 1 ];then
echo "Usage: `basename $0` FILE NAME"
exit 1
fi

sed -i 's/^s*./U&E/g' $@ #capitalize first letter from a paragraf/new line
sed -i 's/[.!?]s*./U&E/g' $@ #capitalize all letters that follow a dot, ? or !





For your special case, things became slightly:



#!/bin/bash

#check if a file is given as argument
if [ $# -ne 1 ];then
echo "Usage: `basename $0` FILE NAME"
exit 1
fi

sed -i '1s/^s*./U&E/g' $@ #capitalize first letter from the file
sed -i 's/.s*./U&E/g' $@ #capitalize all letters that follow a dot

#check if the a line ends in dot, ? or ! character and
#if yes capitalize first letter from the next line
next_line=0
cat $@ | while read line ;do
next_line=$[$next_line+1]
lastchr=${line#${line%?}}
if [ "$lastchr" = "." ] || [ "$lastchr" = "!" ] || [ "$lastchr" = "?" ]; then
sed -i "$[$next_line+1]s/^s*./U&E/g" $@
fi
done





Also, you can consult this tutorial: Unix - Regular Expressions with SED to see how to work in these situations.


[#29876] Wednesday, January 11, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rvousnove

Total Points: 456
Total Questions: 130
Total Answers: 98

Location: El Salvador
Member since Sun, Sep 12, 2021
3 Years ago
;