I have several files that I need to add a "!" to the beginning, just on the first line. I still need to keep the first line's content, just add a "!" as the first character.
Any help would be really appreciated.
Thanks!
Edit: The only thing I could figure out so far was to do the following:
$a = Get-Content 'hh_Regulars3.csv'
$b = '!'
Set-Content 'hh_Regulars3-new.csv' -value $b,$a
This just added the "!" to the top of the file, instead of to the beginning of the first line.
You sent an array to
Set-Content
with$b,$a
. Each array item will be given its own line as you have seen. It would displayed the same way on the prompt if executed.As long as the file is not too big read it in as one string and add the character in.
If you only have PowerShell 2.0 then
Out-String
would work in place of-Raw
The brackets are important to be sure the file is read in before it goes to through the pipeline. It allows us to both read and write on the same pipeline.
If the file is larger look into using
StreamReader
s andStreamWriter
s. This would also have to be used if the trailing new line, created by theAdd-Content
andSet-Content
, is not warranted.Late to the party, but thought this might be useful. I needed to perform the operation over a thousand+ large files, and needed something a little more robust and less prone to OOM exceptions. Ended up just writing it leveraging .Net libraries:
Usage:
This oneliner might works :
Try this: