从txt文件中删除最后一个字符

时间:2015-08-14 06:44:51

标签: powershell

我需要删除文本文件中的最后一个字符并设置此内容。首先,我必须找到最后一个角色的位置。

$dest= "K:\test.txt"

$count_characters= (Get-Content $dest | Measure-Object -Character).Characters

现在我知道了一些字符 - 最后一个字符($count_characters)我必须删除并设置内容。有可能吗?

1 个答案:

答案 0 :(得分:0)

我首先使用数组索引-1访问最后一行。然后,您可以使用一个简单的正则表达式来捕获除最后一个字符之外的整行,并替换它:

$dest= "K:\test.txt"
$replaceCharacter = 'A'

$content = Get-Content $dest
$content[-1] = $content[-1] -replace '^(.*).$', "`$1$replaceCharacter"
$content | Set-Content $dest
相关问题