Blitzcrank
Blitzcrank

Reputation: 967

How to remove some words from all text file in a folder by powershell?

I have a situation that I need to remove some words from all text file in a folder. I know how to do that only in 1 file, but I need to do it automatically for all text files in that folder. I got no idea at all how to do it in powershell. The name of the files are random.

Please help.

This is the code


$txt = get-content c:\work\test\01.i

$txt[0] = $txt[0] -replace '-'

$txt[$txt.length - 1 ] = $txt[$txt.length - 1 ] -replace '-'

$txt | set-content c:\work\test\01.i


Basicly it jsut removes a "-" from first line and last line, but i need to do this on all files in the folder.

Upvotes: 0

Views: 9102

Answers (5)

Jeter-work
Jeter-work

Reputation: 801

Use Get-Childitem to filter for the files you want to modify. Per response to previous question "Powershell, like Windows, uses the extension of the file to determine the filetype."

Also: You will replace ALL "-" with "" on the first and last lines, using what your example shows, IF you use this instead:

 $txt[0] = $txt[0] -replace '-', ''
 $txt[$txt.length - 1 ] = $txt[$txt.length - 1 ] -replace '-', ''

Upvotes: 0

Chand
Chand

Reputation: 320

$files = get-item c:\temp\*.txt
foreach ($file in $files){(Get-Content $file) | ForEach-Object {$_ -replace 'ur word','new word'}  | Out-File $file}

I hope this helps.

Upvotes: 0

NAB
NAB

Reputation: 11

Here is a full working example:

Get-ChildItem c:\yourdirectory -Filter *.txt | Foreach-Object{
(Get-Content $_.FullName) | 
Foreach-Object {$_ -replace "what you want to replace", "what to replace it with"} | 
Set-Content $_.FullName
}

Now for a quick explanation:

  • Get-ChildItem with a Filter: gets all items ending in .txt
  • 1st ForEach-Object: will perform the commands within the curly brackets
  • Get-Content $_.FullName: grabs the name of the .txt file
  • 2nd ForEach-Object: will perform the replacement of text within the file
  • Set-Content $_.FullName: replaces the original file with the new file containing the changes

Important Note: -replace is working with a regular expression so if your string of text has any special characters

Upvotes: 1

Shay Levy
Shay Levy

Reputation: 126762

Get-ChildItem c:\yourfolder -Filter *.txt | Foreach-Object{
   ... your code goes here ...
   ... you can access the current file name via $_.FullName ...
}

Upvotes: 1

Loïc MICHEL
Loïc MICHEL

Reputation: 26150

something like this ?

ls c:\temp\*.txt | %{ $newcontent=(gc $_) -replace "test","toto"  |sc $_ }

Upvotes: 0

Related Questions