1

How to write script in powershell which finds given string in all files in given directory and changes it to given second one ?

thanks for any help, bye

3 Answers 3

1

Maybe something like this

    $files = Get-ChildItem "DirectoryContainingFiles"
    foreach ($file in $files) 
    {
    $content = Get-Content -path $file.fullname
    $content | foreach {$_ -replace "toreplace", "replacewith"} | 
Set-Content $file.fullname
    }
Sign up to request clarification or add additional context in comments.

Comments

1

If the string to replace spans multiple lines then using Get-Content isn't going to cut it unless you stitch together the output of Get-Content into a single string. It's easier to use [io.file]::ReadAllText() in this case e.g.:

Get-ChildItem | Where {!$_.PSIsContainer} | 
    Foreach { $txt = [IO.File]::ReadAllText($_.fullname); 
              $txt -replace $old,$new; $txt | Out-File $_}

Note with with $old, you may need to use a regex directive like '(?s)' at the beginning to indicate that . matches newline characters also.

Comments

0

I believe that you can get the list of all files in a directory (simple?). Now comes the replacement part. Here is how you can do it with power shell:

type somefile.txt | %{$_ -replace "string_to_be_replaces","new_strings"}

Modify it as per your need. You can also redirect the output to a new file the same way you do other redirection (using: >).

To get the list of files, use:

Get-ChildItem <DIR_PATH> -name

1 Comment

I believe that you can get the list of all files in a directory (simple? -> not really cause I dont use powershell at all but its the only one scripting language I can use in this environment

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.