0

I would like to change _ to - in all .md files from folder FOO. The code below does what I need but I don't how to save results in folder FOO or some other...

$mdfiles = gci *.md
gc $mdfiles | ForEach-Object {if ( $_ -match '^!') {$_ -replace '_', '-'} else {$_}} | out-file ...
2
  • 1
    Did you try checking the examples from the documentation? Commented Feb 2, 2022 at 21:20
  • Thanks for the answer Santiago, Yes, I checked official documentation but there I can't find how to output multiple (100+) files after replacing to 100+ same or new files, not to single one. This command works fine if I try to change only one file. gc .\foo.md | ForEach-Object {if ( $_ -match '^!') {$_ -replace '_', '-'} else {$_}} | out-file foo1.md My last atempt was this, but this command also create only one file gc $mdfiles | ForEach-Object {if ( $_ -match '^!') {$_ -replace '_', '-'} else {$_}} | out-file $(".\" + $mdfiles.basename + "-new.md") Commented Feb 2, 2022 at 22:11

1 Answer 1

1

A ForEach-Object is needed to iterate over the file names as well. Ternary expressions are in PowerShell Core, but I am not sure about Windows PowerShell. This is not tested, but might give a start.

Get-ChildItem -File -Path '.' -Filter '*.md' |
    ForEach-Object {
        $OutFile = ".\foo\$($_.Name)"
        Get-Content -Path $_.FullName |
            ForEach-Object { ($_ -match '^!') ? ($_ -replace '_','-') : ($_) } |
            Out-File -FilePath $OutFile
    }

Also, it is bad practice to use alias commands in a stored script.

Sign up to request clarification or add additional context in comments.

Comments

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.