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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With