gpt4 book ai didi

powershell - 如何替换字符串/文件末尾的字符?

转载 作者:行者123 更新时间:2023-12-03 00:42:32 24 4
gpt4 key购买 nike

在使用 PowerShell 格式化时,我试图删除文件末尾的恶意逗号。相关文件包含用户的城市、地区和国家/地区。

示例:

San Diego, California, US, 

But I want it to be:

San Diego, California, US

How can I remove this last ', ' at the end using -replace?My code doesn't work below:

(Get-Content file.txt) | ForEach-Object {
$_ -replace ', ', ''
} | Set-Content file.txt

我只需要一种方法来检测文件中出现的最后一个“,”,而无需删除文件中存在的每个逗号。

最佳答案

您需要将表达式锚定在字符串的末尾。在用 $ 字符完成的正则表达式中。添加 \s* 如果您想忽略最后一个逗号后的尾随空格:

$_ -replace ',\s*$'

关于powershell - 如何替换字符串/文件末尾的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57522396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com