How can I search the first line and the last line in a text file?


I need to only search the 1st line and last line in a text file to find a “-” and remove it.
How can I do it?
I tried select-string, but I don’t know to find the 1st and last line and only remove “-” from there.

Here is what the text file looks like:

Something like this?


Ok, so after looking at this for a while, I decided there had to be a way to do this with a one liner. Here it is:

Here is a breakdown of what this is doing:

First, the aliases for those now familiar. I only put them in because the command is long enough as it is, so this helps keep things manageable:

  1. gc means Get-Content
  2. % means Foreach
  3. $_ is for the current pipeline value (this isn’t an alias, but I thought I would define it since you said you were new)

Ok, now here is what is happening in this:

  1. (gc "c:\myfile.txt") | –> Gets the content of c:\myfile.txt and sends it down the line
  2. % –> Does a foreach loop (goes through each item in the pipeline individually)
  3. -Begin {$test = (gc "c:\myfile.txt" | select -first 1 -last 1)} –> This is a begin block, it runs everything here before it goes onto the pipeline stuff. It is loading the first and last line of c:\myfile.txt into an array so we can check for first and last items
  4. -Process {if ( $_ -eq $test[0] -or $_ -eq $test[-1] ) –> This runs a check on each item in the pipeline, checking if it’s the first or the last item in the file
  5. { $_ -replace "-" } else { $_ } –> if it’s the first or last, it does the replacement, if it’s not, it just leaves it alone
  6. | Set-Content "c:\myfile.txt" –> This puts the new values back into the file.

Please see the following sites for more information on each of these items:

Get-Content uses
Get-Content definition
The Pipeline
Begin and Process part of the Foreach (this are usually for custom function, but they work in the foreach loop as well)
If … else statements

So I was thinking about what if you wanted to do this to many files, or wanted to do this often. I decided to make a function that does what you are asking. Here is the function:

This will create a command called Replace-FirstLast. It would be called like this:

The -Replacewith is optional, if it is blank it will just remove (default value of ""). The -Regex is looking for a regular expression to match your command. For information on placing this into your profile check this article

Please note: If you file is very large (several GBs), this isn’t the best solution. This would cause the whole file to live in memory, which could potentially cause other issues.


How can I search the first line and the last line in a text file? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply