Home > Mobile >  Add eighth and ninth lines to all *.txt files
Add eighth and ninth lines to all *.txt files

Time:10-17

i have more than 100 txt files in C:\myfolder*.txt when i run this script from "C:\myfolder" i can add eighth and ninth lines to somename.txt

@echo off
powershell "$f=(Get-Content somename.txt);$f[8]='heretext1';$f | set-content somename.txt"
powershell "$f=(Get-Content somename.txt);$f[9]='heretext2';$f | set-content somename.txt"

but how can i add eighth and ninth lines to all *.txt files located in path C:\myfolder*.txt Can someone explain me how to do it please...

CodePudding user response:

Thank you for your post But i need to use for all *.txt files in directory C:\myfolder the code i've posted is works fine if you know exactly the name of txt file. I have more than 100 txt files and these files with different names.

CodePudding user response:

Easiest solution I can think of is using the -Index parameter provided in Select-Object for that.

Get-ChildItem -Path .\Desktop\*.txt | % { Get-Content $_.FullName | Select-Object -Index 7,8 } |
    Out-File -FilePath .\Desktop\index.txt 

Edit: based on your post.

CodePudding user response:

Perhaps something like this PowerShell script would suit your task:

Get-ChildItem -Path 'C:\myfolder' -Filter '*.txt' | ForEach-Object {
    $LineIndex = 0
    $FileContent = Switch -File $_ {Default {
            $LineIndex  
            If ($LineIndex -Eq 8) {@'
                heretext1
                heretext2
                '@}
            $_}}
    Set-Content -Path $_ -Value $FileContent}

CodePudding user response:

You need to call Get-ChildItem with your file-name pattern, C:\myfolder\*.txt, and process each matching file via ForEach-Object

@echo off

powershell "Get-ChildItem C:\myfolder\*.txt | ForEach-Object { $f=($_ | Get-Content -ReadCount 0); $f[8]='heretext1'; $f[9]='heretext2'; Set-Content $_.FullName $f }"
  • Related