0

In Powershell script, I have Hashtable contains personal information. The hashtable looks like

{first = "James", last = "Brown", phone = "12345"...}

Using this hashtable, I would like to replace strings in template text file. For each string matches @key@ format, I want to replace this string to value that correspond to key in hashtable. Here is a sample input and output:

input.txt

My first name is @first@ and last name is @last@. 
Call me at @phone@

output.txt

My first name is James and last name is Brown. 
Call me at 12345  

Could you advise me how to return "key" string between "@"s so I can find their value for the string replacement function? Any other ideas for this problem is welcomed.

2 Answers 2

3

You could do this with pure regex, but for the sake of readability, I like doing this as more code than regex:

$tmpl = 'My first name is @first@ and last name is @last@. 
Call me at @phone@'

$h = @{
    first = "James"
    last = "Brown"
    phone = "12345"
}

$new = $tmpl

foreach ($key in $h.Keys) {
    $escKey = [Regex]::Escape($key)
    $new = $new -replace "@$escKey@", $h[$key]
}

$new

Explanation

$tmpl contains the template string.

$h is the hashtable.

$new will contain the replaced string.

  1. We enumerate through each of the keys in the hash.
  2. We store a regex escaped version of the key in $escKey.
  3. We replace $escKey surrounded by @ characters with the hashtable lookup for the particular key.

One of the nice things about doing this is that you can change your hashtable and your template, and never have to update the regex. It will also gracefully handle the cases where a key has no corresponding replacable section in the template (and vice-versa).

Sign up to request clarification or add additional context in comments.

1 Comment

Works Perfect. Appreciate your help.
2

You can create a template using an expandable (double-quoted) here-string:

$Template = @"
My first name is $($hash.first) and last name is $($hash.last). 
Call me at $($hash.phone)
"@

$hash = @{first = "James"; last = "Brown"; phone = "12345"}

$Template

My first name is James and last name is Brown. 
Call me at 12345

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.