Reading Specific Lines from a Text File

Ask your PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 4 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
azeiler
Posts: 12
Last visit: Thu Jan 20, 2022 4:44 pm

Reading Specific Lines from a Text File

Post by azeiler »

Is there a very efficient way to read specific lines from a text file? Say I wanted to read lines 54 through 78 of a text file, what would the most efficient way to do that be?

Get-Content seems to be extremely inefficient with large files. Elsewhere I've seen suggestions like:

Get-Content "file.txt" | Select-Object -Index (54..78)

Correct me if I'm wrong, but isn't this method simply reading the entire file first, and then filtering all the content? So that wouldn't be any more efficient then using Get-Content by itself and then using Indexing to grab the lines you want.

Currently I am able to use a Select-String operation to determine *which* lines to bring in. Now I would like to know if there's an easy way to say "read ONLY these certain lines and save them to a variable."
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Reading Specific Lines from a Text File

Post by jvierra »

That reads the whole file. With text files we have no options of selecting a line. We can only read the file and detect lines. You must read the whole file then find the lines. You can try the following as it may be slightly faster especially for the lines at the beginning of the file.

Get-Content <file> -TotalCount 78 | select -skip 53
This topic is 4 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked