1

Assume that the word child had to be replaced with son in a file consisting of sentences (not a list of words).

It isn't a straight string replacement; for example, the following should not happen:

children should not be changed to sonren

but the following should happen:

child. should be changed to son.

child! should be changed to son!

Basically, the text that is to be replaced must be an independent word and the word separators must be preserved.

How can this be done without hard-coding for every possible word separator?

Yashas
  • 113

1 Answers1

2

You can achieve this with sed command:

sed -i 's/\<child\>/son/' /path/to/your/file

-i[SUFFIX], --in-place[=SUFFIX]

edit files in place (makes backup if extension supplied). The default operation mode is to break symbolic and hard links. This can be changed with --follow-symlinks and --copy.


Considering your example, with the following test file:

child
child.
child!
children

Run the command and you'll get:

son
son.
son!
children

EDIT: To manage case in which you have more than one time the word child on the same line, you have to add g in the command: sed -i 's/\<child\>/son/g' /path/to/your/file