Monday, October 3, 2016

Can you filter the contents of a text file with PowerShell?

In order to work with text files you should know where the text file is stored (saved) in your directory. Once you have the file reference; if you just want to open the file, you could call Notepad from within Powershell like this (type this in the powershell prompt and it will open the file (I am using a file in one of my directories):

PS C:\Users\Jayaram> notepad.exe "C:\Users\Jayaram\Documents\Blog2016\HodentekPlus2016\NoblePrizeMedicine2016.txt"

However if you want to see the contents of the file on your dos screen and filter it you need to use the Get-Content commandlet as shown:

Once you have a file you can search through the text as shown here (here I am looking for all instances of 2016:

PS C:\Users\Jayaram> get-content  "C:\Users\Jayaram\Documents\Blog2016\HodentekPlus2016\NoblePrizeMedicine2016.txt"|Select-String -Pattern "2016"

Yoshinori Ohsumi gets the 2016 Noble Prize for Medicine
Physics 10/4 2016
Chemistry 10/5/2016
Peace 10/6/2016
Literature 10/29/2016

Note: RegEx has enough power to search for almost anything.

No comments: