-1

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!

1 Answers1

1

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

Update

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:

  • it expects that the string you search for occurs only once each line.
  • it replaces the searched string only if it's a distinct word
  • you can accidentally incorporate any python regex syntax into the search param
Tamas Rev
  • 7,008
  • 5
  • 32
  • 49
  • Is it possible to add the text to be replaced into the command? For example: `replacer.py "var_" ExampleInput.txt alpha beta gamma` – AvidLearner Jun 08 '17 at 13:01
  • Yes, you can allocate one more sys.argv param for that. In this case `search = sys.argv[1]`, `input_file = sys.argv[2]` and `replacements = sys.argv[3:]`. You'll need to rewrite the command params check at the beginning, i.e. `if len(sys.argv) < 4: ...`. The search would be `searcher = re.compile("^"+search+"\\b")`. The replacement would be `re.sub("^"+search+"\\b", line.rstrip(), ...)` – Tamas Rev Jun 08 '17 at 13:50