2012-10-24 66 views
0

我是PowerShell的新手,希望在文本文件中的某些场景中替换CRLF。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 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。

我试过下面,只是为了摆脱所有的CRLF的,这不工作:

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

我读过PowerShell中的MSDN,可以在不同线路上替换文本,只是没有结束多行这样的:(

我在对Windows 7的家庭测试,但这是工作,并会在Vista上。

+0

我现在意识到,那获取内容读取文件中,在串线和删除CRLF? - 我可以这样使用:[System.IO.File] :: ReadAllText(“c:\ test.txt”) - 替换“'r'n [^ B |^E]”,“”| Set-Content c:\ test2.txt 但是这个删除了L和S,在List和Sometest上 – TomEaton

+0

请注意'$ content'是一个数组。你可以通过尝试'$ content.GetType()' – David

回答

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 
+0

来说服你自己,谢谢,这个按预期工作:) – TomEaton

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] 
} 
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 
+0

你能提供一些背景/背景对这个答案吗? –

+1

添加评论内嵌 –

+0

谢谢,+1给你先生。 –