Shell script to add a full stop at the end of each line (that do not contain a full stop) in a file

Viewed 353

I have a file with each line a sentence e.g.

Random stuff,
"First sentence",
"second sentence.",
"Third sentence!"
More Random Stuff,

and so on...

I want to in-place modify only the quoted lines i.e. 2nd, 3rd and 4th line in the example above.

I want to do the following modifications -

  1. Add a full stop at the end of line (if a full stop or exclamation mark is not present)
  2. Make first character capital (if its not already capital)

I have tried the following solution to add a full stop -

sed -i 's/[^!.]",/.",/g' $file

The above command removes the last character of the sentence as -

"First sentenc.",

And if I try the following command -

sed -i 's/[^!.]",/&.",/g' $file

I get result as follows -

"First sentence",.",

My desired output is -

"First sentence.",

How can this problem be solved correctly without getting undesired results as shown above? Also, how can I make the first character capital?

The file after modification should be -

Random stuff,
"First sentence.",
"Second sentence.",
"Third sentence!"
More Random Stuff,
1 Answers

This might work for you (GNU sed):

sed -E '/^".*",/{s/[[:alpha:]]/\U&/;s/([^!?.])",$/\1.",/}' file

Focus only on quoted lines. Uppercase the first alphabetic character and insert a period before the closing quote if it is not an exclamation/question mark or period.

Related