gpt4 book ai didi

regex - Powershell根据长度替换行上的文本

转载 作者:行者123 更新时间:2023-12-03 01:16:59 25 4
gpt4 key购买 nike

我有一组文本文件,其结构如下。

问题陈述:每行可以是80个字符或少于80个字符。如果要在行尾找到80位字符,我想删除任何8位数字。

例如在下面。第1行和第2行是80个字符,每个字符的末尾有8位数字。如此简单地删除最后8位数字,即00100001和00100002。对于第3行和第4行,什么也不做。对于第5行,请再次删除最后8个数字,即00100024。对于第6行,请不要执行任何操作。附言括号内的内容(长度80行1)仅用于说明目的,不属于任何行。

ABCD   some text     00100001  (length 80 Line 1)
EFGH 00100002 (Length 80 Line 2)
ABCD Some text (Length less than 80 Line 3)
XYZD (Length less than 80 Line 4)
MNOP 00100024 (Length 80 Line 5)
ABCD (Length less than 80 Line 6)

上面的结果
ABCD   some text     
EFGH
ABCD Some text
XYZD
MNOP
ABCD

到目前为止,我只能设置它以循环方式读取所有文件,但实际上不能更改文件的内容。我确定我在文件外问题上有问题。
**
#ERROR REPORTING ALL
Set-StrictMode -Version latest
$path = "d:\users\desktop\D2d_Try"
$files = Get-Childitem $path -Recurse | Where-Object { !($_.psiscontainer) }

Function getStringMatch
{
# Loop through all *.txt files in the $path directory
Foreach ($file In $files)
{
$content = Get-Content $file.fullName

$content | foreach-object { if($_.length -eq 80) { if($_ -match "^.{72}([0-9]{8})")
{
$_ -replace "$matches[1]"," " | out-file "c:\$file" -append
}
}
}

}
}

getStringMatch

最佳答案

有很多方法可以解决这个问题。一种解决方案是:

#ERROR REPORTING ALL
Set-StrictMode -Version latest
$path = "d:\users\desktop\D2d_Try"

#Creating function first.
#A function should not depend on a variable outside the function ($files in this case)
Function getStringMatch([System.IO.FileInfo]$File, $OutputPath)
{
Get-Content $File.fullName | ForEach-Object {
#The following replace regex will remove the numbers if they are there and the length is 80, if not it will return it as it was.
$_ -replace "^(.{72})([0-9]{8})$", '$1'
} | Set-Content -Path (Join-Path $OutputPath $File.Name)
}


$files = Get-Childitem $path -Recurse | Where-Object { !($_.psiscontainer) } | % { getStringMatch -File $_ -OutputPath "C:\" }

如果您还想修剪所有行以消除开头和结尾的多余空格,则只需将 $_ -replace ...行更改为:
($_ -replace "^(.{72})([0-9]{8})$", '$1').Trim()

老实说,我不明白为什么只有这8个数字ID才需要匹配80个字符。您可以简单地替换字符串末尾的所有8位ID。要尝试,将上面示例中的 $_ -replace ...行替换为:
$_ -replace '[0-9]{8}$'

关于regex - Powershell根据长度替换行上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27512189/

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