Home > Back-end >  How can I add a line break for every tilde found within the contents of several files found at a pat
How can I add a line break for every tilde found within the contents of several files found at a pat

Time:12-06

I would like to use PowerShell to add a line break for every tilde it finds in a file. The source could contain main .in files which contain tildes.

I have this script so far, and could benefit by some assistance in how to tweak it.

This will work for one file, but not for many:

 (Get-Content -Path '.\amalgamatedack.in') |
    ForEach-Object {$_.Replace('~', "~`r`n")} |
    Set-Content -Path '.\amalgamatedack.in'

CodePudding user response:

# Get all .in files in the current directory
$files = Get-ChildItem -Filter "*.in"

# Loop through each file
foreach ($file in $files) {
    # Read the file content
    $content = Get-Content -Path $file

    # Replace all tildes with a line break
    $newContent = $content -replace "~", "~`r`n"

    # Save the new content to the file
    $newContent | Set-Content -Path $file
}

This script will replace all tildes in all .in files in the current directory with line breaks. You can modify the script to suit your specific needs. For example, you can change the filter used by Get-ChildItem to process only certain types of files, or you can specify a different directory to process files from.

CodePudding user response:

Using Get-ChildItem to find all your .in then follow the same logic, just replace the input and output hardcoded file name for the absolute path of each file (.FullName property).

Your code could also benefit by using Get-Content -Raw, assuming these files are not very big and they fit in memory, reading the content as single multi-line string is always faster.

# If you need to search recursively for the files use `-Recurse`
Get-ChildItem path\to\sourcefolder -Filter *.in | ForEach-Object {
    ($_ | Get-Content -Raw).Replace('~', "~`r`n") |
        Set-Content -Path $_.FullName
}
  • Related