首页 > 解决方案 > 将每行的字符串移动到特定位置

问题描述

在 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:

它现在可以工作了:) 谢谢大家。

标签: powershell

解决方案


您可以使用-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 

推荐阅读