Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a certain line of a file with PowerShell?

Tags:

powershell

I don't have a decent text editor on this server, but I need to see what's causing an error on line 10 of a certain file. I do have PowerShell though...

like image 568
northben Avatar asked Feb 07 '13 19:02

northben


People also ask

How do I print a line from a PowerShell script?

The echo command is used to print the variables or strings on the console. The echo command has an alias named “Write-Output” in Windows PowerShell Scripting language. In PowerShell, you can use “echo” and “Write-Output,” which will provide the same output.

How do you display the contents of a file in PowerShell?

When you want to read the entire contents of a text file, the easiest way is to use the built-in Get-Content function. When you execute this command, the contents of this file will be displayed in your command prompt or the PowerShell ISE screen, depending on where you execute it.

How do I use substring in PowerShell?

The Substring method can be used on any string object in PowerShell. This can be a literal string or any variable of the type string. To use the method we will need to specify the starting point of the string that we want to extract. Optionally we can specify the length (number of characters), that we want to extract.


2 Answers

It's as easy as using select:

Get-Content file.txt | Select -Index (line - 1) 

E.g. to get line 5

Get-Content file.txt | Select -Index 4 

Or you can use:

(Get-Content file.txt)[4] 
like image 174
Frode F. Avatar answered Oct 07 '22 03:10

Frode F.


This will show the 10th line of myfile.txt:

get-content myfile.txt | select -first 1 -skip 9

both -first and -skip are optional parameters, and -context, or -last may be useful in similar situations.

like image 39
northben Avatar answered Oct 07 '22 05:10

northben