H
H
hellos0dna2018-03-08 19:09:55
linux
hellos0dna, 2018-03-08 19:09:55

How to find and replace words in a text file?

Hello! Faced such a problem: how to completely replace words in a text file that start the same way but end differently? For example, you need to completely replace several words that begin with "Repeat". Under the replacement should be "Repeat", "Repetition", "Repeat", "Repeat".
How to do it in Sublime Text or some other editor? Or maybe there is a command for Linux?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pfg21, 2018-03-08
@pfg21

In any streaming text editor capable of regexps, from sed to a one-liner with "perl -pe"

E
eeiaao, 2018-03-09
@eeiaao

sed -i~ 's/\(repeat\w*\)/42/gI' <filename>
We use sed to solve the problem. The -i switch means direct editing of the file (in-place). The tilde behind -i is a suffix that will be added to the name of the original file, it will have a backup in case something goes wrong.
Regular:
s - replacement modifier
(repeat\w*) - look for groups starting with "repeat" followed by any number of character/number/underscore. Backslashes are needed to escape parentheses.
42 - what we replace the desired groups with
g - we are looking for all occurrences
I - case-insensitive search

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question