Blitzcrank
Blitzcrank

Reputation: 967

How to remove words from all text files in a folder?

I have a code like this:

$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

It just removes a - from first line and last line in a text file, but I need to do this for all text files in the directory tree which contains over 5k text files. how should I modify this code?

All name of text files are random.

I need to do this in powershell.

Its a directory tree, under c:\work\test there will be more lvl of sub-folders then contains all text files.

Please help . thanks

Upvotes: 2

Views: 2143

Answers (1)

Frode F.
Frode F.

Reputation: 54881

Get all files by file extension or something a pattern and loop through them. Lets say it's all the files with .i extension. Try:

Get-ChildItem -Path "c:\work\test" -Filter *.i -Recurse | where { !$_.PSIsContainer } | % { 
    $txt = Get-Content $_.FullName; 
    $txt[0] = $txt[0] -replace '-'; 
    $txt[$txt.length - 1 ] = $txt[$txt.length - 1 ] -replace '-';
    $txt | Set-Content $_.FullName
    }

Upvotes: 3

Related Questions