仅在每行的某些列位置中查找和替换字符(Find and Replace character only in certain column positions in each line)

编程入门 行业动态 更新时间:2024-10-28 16:20:38
仅在每行的某些列位置中查找和替换字符(Find and Replace character only in certain column positions in each line)

我正在尝试编写一个脚本来查找前11个字符中的所有句点或每行的最后147个字符(行的固定宽度为193,所以我试图忽略字符12到45)。

首先,我想要一个脚本,它只能从每行的第一个或最后一个部分找到所有句点,但是如果我找到它们,我想用0替换所有句点,但忽略第12到第45行的句点并留下那些到位。 它将扫描目录中的所有* .dat文件,并在子文件夹中创建无期间副本。 到目前为止我有:

$data = get-content "*.dat" foreach($line in $data) { $line.substring(0,12) $line.substring(46,147) }

然后我用> Output.txt运行它,然后执行select-string Output.txt -pattern“。”。 正如你所看到的,我离目标很远,目前我的程序正在将所有文件混合在一起,而我还没有想出如何进行任何替换。

I'm trying to write a script to find all the periods in the first 11 characters or last 147 characters of each line (lines are fixed width of 193, so I'm attempting to ignore characters 12 through 45).

First I want a script that will just find all the periods from the first or last part of each line, but then if I find them I would like to replace all periods with 0's, but ignore periods on the 12th through 45th line and leaving those in place. It would scan all the *.dat files in the directory and create period free copies in a subfolder. So far I have:

$data = get-content "*.dat" foreach($line in $data) { $line.substring(0,12) $line.substring(46,147) }

Then I run this with > Output.txt then do a select-string Output.txt -pattern ".". As you can see I'm a long ways from my goal as presently my program is mashing all the files together, and I haven't figured out how to do any replacement yet.

最满意答案

Get-Item *.dat | ForEach-Object { $file = $_ $_ | Get-Content | ForEach-Object { $beginning = $_.Substring(0,12) -replace '\.','0' $middle = $_.Substring(12,44) $end = $_.Substring(45,147) -replace '\.','0' '{0}{1}{2}' -f $beginning,$middle,$end } | Set-Content -Path (Join-Path $OutputDir $file.Name) } Get-Item *.dat | ForEach-Object { $file = $_ $_ | Get-Content | ForEach-Object { $beginning = $_.Substring(0,12) -replace '\.','0' $middle = $_.Substring(12,44) $end = $_.Substring(45,147) -replace '\.','0' '{0}{1}{2}' -f $beginning,$middle,$end } | Set-Content -Path (Join-Path $OutputDir $file.Name) }

更多推荐

本文发布于:2023-04-29 06:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   位置   Find   Replace   line

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!