对PowerShell的awk命令

时间:2014-04-22 21:24:04

标签: bash powershell awk

在powershell中是否有像awk这样的命令?

我想执行此命令:

awk '
BEGIN {count=1}
/^Text/{text=$0}
/^Time/{time=$0}
/^Rerayzs/{retext=$0}
{
  if (NR % 3 == 0) {
    printf("%s\n%s\n%s\n", text, time, retext) > (count ".txt")
    count++
  }
}' file

到powershell命令。

1 个答案:

答案 0 :(得分:4)

通常我们希望看到您尝试过的内容。它至少表明你正在努力,我们不只是为你做你的工作。我认为你是PowerShell的新手,所以我只想给你一个答案,希望你用它来学习和扩展你的知识,并希望将来有更好的问题。

我很确定这将完成与你所布置的相同的事情。你必须给它一个输入数组(文本文件的内容,一个字符串数组,类似的东西),它将生成几个文件,具体取决于它为treo“Text”,“Time”找到的匹配数量,和“Rerayzs”。它会将它们命名为Text,然后是一个带有Time的新行,然后是一个带有Rerayzs的新行。

$Text,$Time,$Retext = $Null
$FileCounter = 1
gc c:\temp\test.txt|%{
    Switch($_){
        {$_ -match "^Text"} {$Text = $_}
        {$_ -match "^Time"} {$Time = $_}
        {$_ -match "^Rerayzs"} {$Retext = $_}
    }
    If($Text -and $Time -and $Retext){
        ("{0}`n{1}`n{2}") -f $Text,$Time,$Retext > "c:\temp\$FileCounter.txt"
        $FileCounter++
        $Text,$Time,$Retext = $Null
    }
}

这将获得文件C:\Temp\Test.txt的文本,并将编号的文件输出到同一位置。我测试的文件是:

Text is good.
Rerayzs initiated.
Stuff to not include
Time is 18:36:12
Time is 20:21:22
Text is completed.
Rerayzs failed.

我留下了2个文件作为输出。第一个读到:

Text is good.
Time is 18:36:12
Rerayzs initiated.

第二个读到:

Text is completed.
Time is 20:21:22
Rerayzs failed.