gpt4 book ai didi

powershell - 仅在文本文件中删除第 5 列的空格

转载 作者:行者123 更新时间:2023-12-03 10:04:06 26 4
gpt4 key购买 nike

我有一个来自 API 的文本文件,我只需要从特定列(第 5 列)中删除空格

例子:

"Number"|"Message"|"Reference"|"SendFrom"|"CampaignName"
"4478xxxxxxxx"|"Test message from test system"|"104"|"dunno"|"Campaign Name Here 2"
"4479xxxxxxxx"|"Test message from test system"|"105"|"dunno"|"Campaign Name Here 2"

我需要输出如下:

"Number"|"Message"|"Reference"|"SendFrom"|"CampaignName"
"4478xxxxxxxx"|"Test message from test system"|"104"|"dunno"|"CampaignNameHere2"
"4479xxxxxxxx"|"Test message from test system"|"105"|"dunno"|"CampaignNameHere2"

所以只有最后一列的空格被删除了,文件的其余部分没有。

我能够隔离最后一列并删除空格:

$columnToGet4 = 4
$columns4 = gc $Report |
%{ $_.Split("|",[StringSplitOptions]"RemoveEmptyEntries")[$columnToGet4] }

$columns4 = $columns4 -replace '\s',''

但尝试将数据重新组合在一起是行不通的。

关于如何实现这一点有什么建议吗?

谢谢

最佳答案

您可以为此使用 PowerShell 的 CSV 处理:

# Import the file as if it was a CSV separated by the pipe,
# and process each row

Import-Csv -LiteralPath 'c:\temp\input.txt' -Delimiter '|' |
ForEach-Object {

# Replace spaces in the campaignName column, by name
$_.CampaignName = $_.CampaignName -replace '\s'

# and output the changed row item, for export to file
$_

} | Export-Csv -LiteralPath 'c:\temp\output.txt' -Delimiter '|' -NoTypeInformation

或者纯文本处理和正则表达式替换:

Get-Content -LiteralPath 'c:\temp\input.txt' | ForEach-Object {
$_ -replace '\s(?=[^|]+$)'
} | Set-Content -LiteralPath 'c:\temp\output.txt' -Encoding ASCII

正则表达式挑选出“之后线路上不再有管道的空间”(可能不是一个有效的假设)。

或者您可以使用纯文本处理,找出最后一个竖线字符所在的位置:

Get-Content -LiteralPath 'c:\temp\input.txt' | foreach-object {

$afterLastPipe = $_.lastindexof('|')+1

$_.Substring(0, $afterLastPipe) + $_.Substring($afterLastPipe).Replace(' ', '')

} | Set-Content...

同样,假设没有更多的管道可能不是一个有效的假设,特别是如果引号内可能有管道的话。

关于powershell - 仅在文本文件中删除第 5 列的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55413314/

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