I would like to replace all "var_"
var_
Hello
var_
Whats
var_
Up?
...
with words from this list
alpha
beta
gamma
...
so the end result is
alpha
Hello
beta
Whats
gamma
Up?
...
Would appreciate help on achieving this!
I would like to replace all "var_"
var_
Hello
var_
Whats
var_
Up?
...
with words from this list
alpha
beta
gamma
...
so the end result is
alpha
Hello
beta
Whats
gamma
Up?
...
Would appreciate help on achieving this!
This is sort of impossible / overly complicated with a regex. However, if you combine it with a programming language, you can get it done quickly. E.g. in python it would look like this:
import sys
import re
import fileinput
if len(sys.argv) < 3:
exit("Usage: " + sys.argv[0] + " <filename> <replacements>")
input_file = sys.argv[1]
replacements = sys.argv[2:]
num_of_replacements = len(replacements)
replacement_index = 0
searcher = re.compile("^var_\\b")
for line in fileinput.input(input_file, inplace=True, backup='.bak'):
match = searcher.match(line)
if match is None:
print(line.rstrip())
else:
print(re.sub("^var_\\b", line.rstrip(), replacements[replacement_index]))
replacement_index = replacement_index + 1
Usage: replacer.py ExampleInput.txt alpha beta gamma
It's possible to modify the program to accept the string you search for as the 1st param:
replacer.py "var_" ExampleInput.txt alpha beta gamma
The modified python script looks like this:
import sys
import re
import fileinput
if len(sys.argv) < 4:
exit("Usage: " + sys.argv[0] + " <pattern> <filename> <replacements>")
search = "\\b" + sys.argv[1] + "\\b"
input_file = sys.argv[2]
replacements = sys.argv[3:]
num_of_replacements = len(replacements)
replacement_index = 0
searcher = re.compile(search)
for line in fileinput.input(input_file, inplace=True, backup='.bak'):
match = searcher.match(line)
if match is None:
print(line.rstrip())
else:
print(re.sub(search, line.rstrip(), replacements[replacement_index]))
replacement_index = replacement_index + 1
Note: this script still has a few limitations:
search
param