John Kens
John Kens

Reputation: 1679

Looking to remove text from text file using powershell

I'm trying to edit a large plain text document containing various html elements such as the following:

My goal is to remove any <UniqueText> from a text file. I've not worked with powershell much so my knowledge is limited, none less, I gave it a shot.

For replacing all <UniqueText>

get-content "C:\Users\John\Desktop\input.txt" | -replace "\<.*?\>","" | Out-File C:\Users\John\Desktop\output.txt

The above script gives the following error:

-replace : The term '-replace' is not recognized as the name of a cmdlet, function, script file, or operable program.

Upvotes: 2

Views: 23993

Answers (2)

man.shahi
man.shahi

Reputation: 21

i use this command

Get-Content C:\Windows\System32\drivers\etc\hosts | % {$_ -replace "some text","" -replace "some text",""} |Out-File C:\Windows\System32\drivers\etc\hosts

but the file become empty.

Upvotes: 1

Paxz
Paxz

Reputation: 3036

When you use -replace you have to be sure that you parse the string correctly to the call. There are two ways you can solve your problem:

1. Use foreach to go through each line of the file and use -replace on each line (this might be helpfull if you want to do something else with the lines):

get-content "C:\Users\John\Desktop\input.txt" | % {$_ -replace "\<.*?\>",""} | Out-File C:\Users\John\Desktop\output.txt

% is the alias for foreach

$_ is element of the foreach, so each line of the file

2. Use replace on the file without going through each line:

(get-content "C:\Users\John\Desktop\input.txt") -replace "\<.*?\>","" |  Out-File C:\Users\John\Desktop\output.txt

Upvotes: 5

Related Questions