0

私は PowerShell を初めて使用し、テキスト ファイル内のいくつかのシナリオで CRLF を置き換えたいと考えています。

テキストファイルの例は次のとおりです。

Begin 1 2 3
End 1 2 3
List asd asd
Begin 1 2 3
End 1 2 3
Begin 1 2 3
End 1 2 3
Sometest asd asd
Begin 1 2 3

行が Begin または End で始まっていない場合、その行を前の行に追加したいと考えています。

したがって、望ましい結果は次のようになります。

Begin 1 2 3
End 1 2 3 List asd asd
Begin 1 2 3
End 1 2 3
Begin 1 2 3
End 1 2 3 Sometest asd asd
Begin 1 2 3

ファイルはタブ区切りです。したがって、Begin と End の後は TAB です。

すべてのCRLFを取り除くためだけに、以下を試しましたが、うまくいきません:

$content = Get-Content c:\test.txt
$content -replace "'r'n","" | Set-Content c:\test2.txt

PowerShell で MSDN を読んだことがありますが、このように複数行ではなく、さまざまな行のテキストを置き換えることができます:(

私は自宅で Windows 7 をテストしていますが、これは仕事用であり、Vista で使用する予定です。

4

3 に答える 3

2
# read the file
$content = Get-Content file.txt

# Create a new variable (array) to hold the new content
$newContent = @()

# loop over the file content    
for($i=0; $i -lt $content.count; $i++)
{  
  # if the current line doesn't begin with 'begin' or 'end'   
  # append it to the last line םכ the new content variable
  if($content[$i] -notmatch '^(begin|end)')
  {
    $newContent[-1] = $content[$i-1]+' '+$content[$i]
  } 
  else
  {
    $newContent += $content[$i]
  }
}

$newContent
于 2012-10-25T07:32:05.237 に答える
1

この一行についてどう思いますか?

gc "beginend.txt" | % {}{if(($_ -match "^End")-or($_ -match "^Begin")){write-host "`n$_ " -nonewline}else{write-host $_ -nonewline}}{"`n"}

Begin 1 2 3
End 1 2 3 List asd asd
Begin 1 2 3
End 1 2 3
Begin 1 2 3
End 1 2 3 Sometest asd asd
Begin 1 2 3
于 2012-10-25T04:09:04.760 に答える
0
$data = gc "beginend.txt"

$start = ""
foreach($line in $data) {
    if($line -match "^(Begin|End)") {
        if($start -ne "") {
            write-output $start
        }
        $start = $line
    } else {
        $start = $start + " " + $line
    }
}

# This last part is a bit of a hack.  It picks up the last line
# if the last line begins with Begin or End.  Otherwise, the loop
# above would skip the last line.  Probably a more elegant way to 
# do it :-)
if($data[-1] -match "^(Begin|End)") {
    write-output $data[-1]
}
于 2012-10-25T01:15:21.933 に答える