前置“!"到文件第一行的开头 [英] Prepend "!" to the beginning of the first line of a file
问题描述
我有几个文件需要添加!"到开头,就在第一行.我仍然需要保留第一行的内容,只需添加一个!"作为第一个字符.
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.
任何帮助将不胜感激.
谢谢!
到目前为止,我唯一能想到的是执行以下操作:
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.
推荐答案
您使用 $b,$a
向 Set-Content
发送了一个数组.正如您所见,每个数组项都有自己的一行.如果执行,它将在提示上以相同的方式显示.
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.
$path = 'hh_Regulars3.csv'
"!" + (Get-Content $path -Raw) | Set-Content $path
如果您只有 PowerShell 2.0,那么 Out-String
将代替 -Raw
If you only have PowerShell 2.0 then Out-String
would work in place of -Raw
"!" + (Get-Content $path | Out-String) | Set-Content $path
括号对于确保文件在通过管道之前被读入很重要.它允许我们在同一个管道上读写.
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.
如果文件较大,请考虑使用 StreamReader
s 和 StreamWriter
s.如果不保证由 Add-Content
和 Set-Content
创建的尾随新行,也必须使用此方法.
If the file is larger look into using StreamReader
s and StreamWriter
s. This would also have to be used if the trailing new line, created by the Add-Content
and Set-Content
, is not warranted.
这篇关于前置“!"到文件第一行的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!