Click here to Skip to main content
15,506,384 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Good day, I want to mix all the words between them, but my method with `@content.Split ` and `replace` seems doesn't change too many words between them. Can anyone help me?

What I have tried:

$fileName = "C:\Folder1\file.txt"
  $newfilename = "C:\Folder1\newfile.txt"
  # Get content of file
  $content = Get-Content -Path $fileName -Raw -Encoding UTF8
  $words = (((($content.Split(" ")).Replace(".","")).Replace(",","")).Replace("`n",""))
  #Define function
  Function Create-Words {
      $script:word1 = Get-Random -InputObject $words # get first random word from word list
      $script:word2 = Get-Random -InputObject $words  # get second random word from word list
      Write-Host "First word: " $script:word1 -ForegroundColor Green # write output word1
      Write-Host "Second word: " $script:word2 -ForegroundColor Magenta # write output of word2
  # Execute function
  # Replace random word1 with random word2 and write file
  $content.Replace("$word1", "$word2") | Out-File -FilePath "$newfilename" -force
Updated 20-May-21 7:28am
Richard MacCutchan 18-May-21 11:38am    
The code replaces one random word with another chosen at random. So it depends on the number of occurrences of that word. If you want more changes then create a loop.
Richard MacCutchan 18-May-21 11:50am    
You also have the problem that your replacements will be string based not word. So for example in the text:
The rain in Spain falls mainly in the plain.

changing 'in' to 'custard' will give you
The racustard custard Spacustard falls macustardly custard the placustard.
Richard Deeming 20-May-21 12:22pm    
Mmmmm, macustardly custard! 🤣
Richard MacCutchan 20-May-21 12:25pm    

1 solution

<pre> ((Get-Content -Path C:\Folder1\file.txt -Raw ) -split "\s+" | 
     Sort-Object {Get-Random} ) -join ' ' |
         Out-File -FilePath C:\Folder1\NewFile.txt
Share this answer
Dimiter2011 2-Nov-21 13:43pm    
Thanks Rob. Works like a charm.
((Get-Content .\p.txt -Raw ) -split "\s+" | Sort-Object {Get-Random} ) -join ' ' | Out-File .\pNew.txt

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900