Click here to Skip to main content
15,032,967 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
  Create-Words
  # Replace random word1 with random word2 and write file
  $content.Replace("$word1", "$word2") | Out-File -FilePath "$newfilename" -force
Posted
Updated 20-May-21 6:28am
Comments
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
   
:laugh:

1 solution

PowerShell
<pre> ((Get-Content -Path C:\Folder1\file.txt -Raw ) -split "\s+" | 
     Sort-Object {Get-Random} ) -join ' ' |
         Out-File -FilePath C:\Folder1\NewFile.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