PowerShell在某些情况下替换CRLF

时间:2012-10-24 22:58:56

标签: file powershell replace newline

我是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

该文件是Tab Seperated。所以在开始和结束之后,是一个TAB。

我尝试了下面的内容,只是为了摆脱所有CRLF,这不起作用:

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

我已经阅读了PowerShell上的MSDN,可以替换不同行上的文本,而不是像这样多行:(

我正在家中测试Windows 7,但这是为了工作,将在Vista上。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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]
}