1

I have to replace a phone number in a document but when there is no phone number from mu user I have to delete this row The default document looks like this:

company
street
T: +00 xxx xxx xxx  #phone
F: +00 xxx xxx xxx  #Fax
M: +00 xxx xxx xxx  #Mobile

When for example a user has no mobile phone I have to delete this row

$content = $content -replace "M:",""
$content = $content -replace "+00",""
$content = $content -replace "xxx xxx xxx",""

But I'm getting this error

The regular expression pattern +39 is not valid.
At line:65 char:1
+ $content = $content -replace "+39",""
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (+39:String) [], RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

How can I now delete this row when power shell doesn't want my + in a string

Delete the row:

After deleting successful the mobile number document looks like this:

company
street
T: +00 xxx xxx xxx  #phone
F: +00 xxx xxx xxx  #Fax

more information

But it should look like this

company
    street
    T: +00 xxx xxx xxx  #phone
    F: +00 xxx xxx xxx  #Fax
    more information
3
  • can you provide an example line where phone number needs to get deleted? Commented Jun 8, 2016 at 13:50
  • Can you also show what should be in the end? Commented Jun 8, 2016 at 13:57
  • i hope you understand now what i mean :) Commented Jun 8, 2016 at 14:02

2 Answers 2

2

Don't use regex replace, but use String.Replace:

$content = $content.Replace("M:","")
$content = $content.Replace("+00","")
$content = $content.Replace("xxx xxx xxx","")

This should work for you:

$content = Get-Content $filepath | foreach-object { if (!$_.StartsWith("M:")) { $_ } }
$content
Sign up to request clarification or add additional context in comments.

5 Comments

thanks that worked and how can i delete the row no is there space between the next rows
after the row where the mobile number is are other rows with information's. When I set the row with the mobile number to "" (nothing) there is one row without anything in how can i delete this row that there is no more space between the row Fax and the next row
Is it possible to get it as a string array instead of 1 string?
i dont know i'm beginner in powershell i have a rtf document and get the content with : $content = Get-Content $filepath -raw
see update, but regex option could be a bit better here
1

You could also use a regex to filter them:

$content | Where { $_ -notmatch '^M: \+00' }

3 Comments

Damn, beat me to it!
@briantist sorry :-p.
Probably its how you retrieve the $content variable (you have to omit the -raw parameter to get an array. However, you already got an comprehensive answer.

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.