List lines from a text file

There may come a time when you want to display just a few lines from a text file. The following PowerShell code can be used to achieve this.

The examples will be based upon a sample text file containing the lines:


the,1
quick,2
brown,3
fox,4
jumps,5
over,6
the,7
lazy,8
dog,9

1.

In this example, the parameter TotalCount of the Get-Content cmdlet specifies the number of lines from the beginning of a file. The default is -1 (list all lines).

Get-Content -Path myfile.txt -TotalCount 3

Sample output:

the,1
quick,2
brown,3

You can also achieve this with:

Get-Content myfile.txt -First 3

2.

Doing this from the other end, the Get-Content cmdlet parameter Tail lists lines from the end of the file. This parameter specifies the number of lines from the end of a file.

Get-Content -Path myfile.txt -Tail 3

Sample output:

the,7
lazy,8
dog,9

3.

First and last few lines.

If you really wanted to, you could pipe the output from the Get-Content cmdlet into the Select-Object and make use of the First and Last parameters to look at the first few or last lines in the file.

  • First – Gets only the specified number of objects. Enter the number of objects to get.
  • Last – Specifies the number of objects to select from the end of an array of input objects.

Examples

Get-Content -Path myfile.txt | Select-Object -First 3

or

Get-Content -Path myfile.txt | Select-Object -Last 4

Lines in the middle of the file.

To look at lines other than the first or last, we could use the Select-Object parameter Index.

From the documentation:

-Index

Selects objects from an array based on their index values. Enter the indexes in a comma-separated list.

Indexes in an array begin with 0, where 0 represents the first value and (n-1) represents the last value. IE, the array is zero-based.

This means we have to subtract 1 from the line number(s) in question. To look at lines 4,5 and 6 inclusive, we have to specify line numbers 3,4 and 5.

Get-Content -Path myfile.txt | Select-Object -Index 3,4,5

will give you:

fox,4
jumps,5
over,6

Of course, if you’d like to skip some lines, then use the following:

Get-Content -Path myfile.txt | Select-Object -Skip 4

Advertisements
This entry was posted in powershell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s