PowerShell - 从文本文件中查找和复制URL并复制到另一个由Pipe分隔的文本文件

时间:2016-02-05 00:16:08

标签: string powershell copy pipeline select-string

我需要一个 Powershell脚本,它会在任何关键字出现时读取给定文件"匹配:"和"替换:"并将其前面的行复制到另一个文本文件中的新行,该文件由管道分隔并结束。示例如下。

输入

20/01/2016 00:00:18 Some Lines of Text here
20/01/2016 00:00:18 Some Lines of Text here
20/01/2016 00:00:18 Match: /test/OLD/Myfolders/Folders/Folder1/         
20/01/2016 00:00:19 Replace: /test2/NEW/currentfiles/  
20/01/2016 00:00:19 Some Lines of Text here
20/01/2016 00:00:20 Some Lines of Text here
20/01/2016 00:00:20 Some Lines of Text here
20/01/2016 00:00:20 Match: /match/2015/pages/
20/01/2016 00:00:20 Replace: /replace/2016/pages/
20/01/2016 00:00:21 Some Lines of Text here

输出

/test/OLD/Myfolders/Folders/Folder1/|/test2/NEW/currentfiles/|
/match/2015/pages/|/replace/2016/pages/|

所以每次关键字"匹配:"发现它前面的URL被复制到新文本文件中的新行,后面跟着管道和#34;前面的URL:"

/Matching URL/|/Replacing URL/|
/Matching URL/|/Replacing URL/|

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

Get-Content input.txt | ForEach-Object {
    if ($_.tostring().Contains("Match")) {
        $i = $_.tostring().IndexOf("Match")
        $url = $_.ToString().Substring($i+7).Trim() + "|"
    } elseif ($_.tostring().Contains("Replace")) {
        $i = $_.ToString().IndexOf("Replace")
        $url = $url + $_.ToString().Substring($i+9).Trim() + "|"| Out-File ouput.txt -Append
        $url = $null
    }
}