Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Top Line of Text File with PowerShell

Tags:

powershell

I am trying to just remove the first line of about 5000 text files before importing them.

I am still very new to PowerShell so not sure what to search for or how to approach this. My current concept using pseudo-code:

set-content file (get-content unless line contains amount) 

However, I can't seem to figure out how to do something like contains.

like image 525
Buddy Lindsey Avatar asked Jan 15 '10 19:01

Buddy Lindsey


People also ask

How do I remove the first line from a text file in PowerShell?

Avoid the loop variable $i and the comparison with 0 in every loop. Wrap the execution into a try.. finally block to always close the files in use. Make the solution work for an arbitrary number of lines to remove from the beginning of the file.

How do I remove the last line of a file in PowerShell?

count-1) to {($a. count-0) allows it to "remove" the last line. Adjust that number to the desired count to remove a specific line number from the bottom up.

How do I trim in PowerShell?

To trim whitespace from strings, simply call the trim() method with no arguments like below. When the PowerShell Trim () method is not supplied with any parameters then the Char. IsWhiteSpace method is called and all leading and ending whitespace characters found are removed.


2 Answers

While I really admire the answer from @hoge both for a very concise technique and a wrapper function to generalize it and I encourage upvotes for it, I am compelled to comment on the other two answers that use temp files (it gnaws at me like fingernails on a chalkboard!).

Assuming the file is not huge, you can force the pipeline to operate in discrete sections--thereby obviating the need for a temp file--with judicious use of parentheses:

(Get-Content $file | Select-Object -Skip 1) | Set-Content $file 

... or in short form:

(gc $file | select -Skip 1) | sc $file 
like image 178
Michael Sorens Avatar answered Sep 23 '22 12:09

Michael Sorens


It is not the most efficient in the world, but this should work:

get-content $file |     select -Skip 1 |     set-content "$file-temp" move "$file-temp" $file -Force 
like image 32
Richard Berg Avatar answered Sep 22 '22 12:09

Richard Berg