Home > database >  Using Powershell to copy multiple lines by line number
Using Powershell to copy multiple lines by line number

Time:01-31

I have a text file with about 300,000 rows. I need to copy about 188 lines and I have a list of line numbers to extract.

Is there a function that will allow me to do this faster than using crtl G and keying in each line number manually?

Thanks

CodePudding user response:

I would use the very fast switch for this as it processes a text file line-by-line.

This example starts the line indexing at 1.

# the list of line numbers to fetch
$linesToFetch = 1,4,7,9,12
$currentLine  = 1
$result  = switch -File 'D:\Test\test.txt' {
    default { if ($linesToFetch -contains $currentLine  ) { $_ }}
}

# write to file and also display on screen by using -PassThru
$result | Set-Content -Path 'D:\Test\excerpt.txt' -PassThru

CodePudding user response:

you can use get-content:

to get the first 188 lines:

get-content -Path .\yourfile.txt -TotalCount 188 | set-content -Path .\out_path.txt

you can print specific using skip:

Get-Content -Path ".\yourfile.txt" -First 188 | select -Skip 10

to get specific lines:

get-content -Path .\yourfile.txt | Select-Object -Index 0, 1, 2,... | set-content -Path .\out_path.txt
  •  Tags:  
  • Related