How to find and replace the last space in each line of a file in BASH?

bash, regex, replace, sed

Solution

Try this:

sed 's/\(.*\) /\1@/'

Problem

I have a file like this: ``` Once upon a time there lived a cat. The cat lived in the forest. The forest had many trees. ``` I need to replace the last space per line with a "@", e.g.: ``` Once upon a time there lived a@cat. The cat lived in the@forest. The forest had many@trees. ``` I tried `sed 's/ .*$/@/g' file.txt`, but `.*` matches everything and deletes all of the text found there. How can I replace the last space per line with "@"?

Original source