If you are a Linux administrator, you may be familiar with tail, head ad grep commands when reading text files, and they are convenient when looking at log files. (If you are not familiar, we are going to summarize it here.) In a Linux shell, if we want to check the first three lines of a log file, we would execute head -n 3, and to read the last two lines of any given file, we would run tail -n 2.
If we want to check the entire contents of a file, we can use cat file.txt. On the other hand, if we're going to search a specific string within a particular file, we can use cat file.txt | grep "string."
The entire process of reading text files in a Linux bash shell is depicted in the image below.
How about reading text files with PowerShell? That is a piece of cake and more intuitive (since it is a single cmdlet, which helps to save the precious memory slots of my brain already stuffed with all those command names!).
First, to get the entire content of any given file, you can use the Get-Content cmdlet.
Get-Content <file.txt>
If you want the first lines (head) or the end of the file (tail), we can execute these cmdlets:
Get-Content <file.txt> -Head 2 Get-Content <file.txt> -Tail 3
If we want to do something similar to the grep command. We will use the Select-String cmdlet.
Get-Content <file.txt> | Select-String “String”
The entire process that we have just described is depicted in the image below.
More Linux articles
- Linux security and growing cyberthreats: Everything you need to know
- Data transfer between Linux and Windows: Step-by-step guide
- Setting up static IP address for Linux: Easier than you think
- Merging and sorting files in Linux: Easier than you think
- Sending email from Linux terminal: Efficient and powerful solution
More PowerShell Basics articles
- Working with dates in PowerShell revisited
- PowerShell regular expressions: Making string evaluation easier
- PowerShell concatenation: How to use this powerful feature
- What does a question mark mean in PowerShell commands?
- Using Group Policy settings to enforce PowerShell execution policies
More Quick Tips articles
- Fixing Azure Key Vault when moving to a different tenant
- Restore Azure Key Vault using just two PowerShell cmdlets
- This overlooked feature in Visual Studio Code can speed release time
- Enabling Front Door managed certificates in Azure: Status update
- How to quickly check the status of all your Azure services