RookieCoder
RookieCoder

Reputation: 29

Using Powershell to copy multiple lines by line number

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

Upvotes: 1

Views: 922

Answers (2)

Tal Folkman
Tal Folkman

Reputation: 2581

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

Upvotes: 0

Theo
Theo

Reputation: 61148

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

Upvotes: 2

Related Questions