powershell - 将每行的字符串移动到特定位置
问题描述
在 PowerShell 中,如何将每行的字符串移动到特定位置?
例子 :
CXTYPMORDER TEXT IS 'Type of order' ,
CXNUMORD TEXT IS 'Number of order' ,
CXCC TEXT IS 'Code of order' ,
CXDAY TEXT IS 'Day of order' ,
CXMONTH TEXT IS 'Month of order' ,
想要的结果:
CXTYPMORDER TEXT IS 'Type of order' ,
CXNUMORD TEXT IS 'Number of order' ,
CXCC TEXT IS 'Code of order' ,
CXDAY TEXT IS 'Day of order' ,
CXMONTH TEXT IS 'Month of order' ,
编辑 1:
我试过这个:
$newstreamreader = New-Object System.IO.StreamReader("N:\TEMP\TEST\TEST.txt")
$newstreamwriter = New-Object System.IO.StreamWriter("N:\TEMP\TEST\TEST_New.txt")
$eachlinenumber = 1
$position = 0
$numberofspace = 0
while (($readeachline =$newstreamreader.ReadLine()) -ne $null)
{
if($readeachline -match "^(\S+) TEXT IS '([^']+)'"){
$position = $readeachline.IndexOf("TEXT IS")
$numberofspace = 15-$position
$newstring = $readeachline.Insert($position, " " * $numberofspace)
$newstreamwriter.WriteLine($newstring)
}
$eachlinenumber++
}
$newstreamwriter.Close()
编辑 2:
它现在可以工作了:) 谢谢大家。
解决方案
您可以使用-match
正则表达式运算符来匹配和捕获每一行的相关部分,然后构造一个可以轻松格式化以便于阅读的对象:
# Use Get-Content to read the file line by line
$Descriptions = Get-Content path\to\file.txt |ForEach-Object {
# Check if current line is what we're looking for:
if($_ -match "^(\S+) TEXT IS '([^']+)'"){
# Extract capture group values
$EntryName = $Matches[1]
$Description = $Matches[2]
# Create a new object with the extracted values
[pscustomobject]@{
Name = $EntryName
Description = $Description
}
}
}
现在您可以使用Format-Table
它来使其具有可读性:
PS C:\> $Descriptions |Format-Table -AutoSize
Name Description
---- -----------
CXTYPMORDER Type of order
CXNUMORD Number of order
CXCC Code of order
CXDAY Day of order
CXMONTH Month of order
上面使用的正则表达式模式 ( ^(\S+) TEXT IS '([^']+)'
) 描述:
^ # Start of string
( # Start capture group
\S+ # 1 or more non-whitespace characters
) # End capture group
TEXT IS ' # Literal string ` TEXT IS '
( # Start capture group
[^']+ # 1 or more characters that aren't single-quotes
) # End capture group
' # Literal single-quote
推荐阅读
- mysql - 如何修复 SQL 编码中的“ERROR 1064 you have an error in your SQL syntax”
- bash - 如何在 VSC MacOS 上配置 Git Bash
- python - 在熊猫中将行组合成按日期排序的列表
- sql - 使用 join on table 将州的全名更改为缩写
- powershell - 如何通过 Powershell 脚本隐藏/删除输出 csv 中的标头
- asp.net-mvc - 如何将 MVC 4 添加到 VS 2015 中
- python - 减少使用 pandas 或内置函数打开解析大型 TSV 文件的时间
- css - 媒体查询适用于错误的屏幕尺寸
- php - 有没有办法查找/删除孤立文件(SQL 数据库中未列出)?
- android - 无法解决 Cordova 中的 PATH 问题