0

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.

Blitzcrank
  • 917
  • 2
  • 10
  • 19
  • I posted in the duplicate question YOU created(duplicate questions is bad btw). http://stackoverflow.com/questions/14442229/ – Frode F. Jan 21 '13 at 16:14

5 Answers5

1
Get-ChildItem c:\yourfolder -Filter *.txt | Foreach-Object{
   ... your code goes here ...
   ... you can access the current file name via $_.FullName ...
}
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
1

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

Bohemian
  • 412,405
  • 93
  • 575
  • 722
NAB
  • 11
  • 2
0

something like this ?

ls c:\temp\*.txt | %{ $newcontent=(gc $_) -replace "test","toto"  |sc $_ }
Loïc MICHEL
  • 24,935
  • 9
  • 74
  • 103
  • how to only remove a "-" from first line and last line? – Blitzcrank Jan 21 '13 at 14:55
  • $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 – Blitzcrank Jan 21 '13 at 14:58
0
$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.

oz123
  • 27,559
  • 27
  • 125
  • 187
Chand
  • 300
  • 3
  • 13
0

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 '-', ''
Community
  • 1
  • 1
Jeter-work
  • 782
  • 7
  • 22