[英]Copy 2 lines from many into a new file
I have a text file which contains randomly generated data like this: 我有一个文本文件,其中包含随机生成的数据,如下所示:
AllocatedStorage : 5
InstanceName : testdatabase
SnapshotName : testdatabase-05-07-15-00-00
CreateTime : 05/07/2015 00:00:00 AM
AllocatedStorage : 10
InstanceName : testdb
SnapshotName : testdb-10-07-15-00-00
CreateTime : 10/07/2015 00:00:00 AM
I want to write both the snapshotname as well as createtime to be written to another file, of all the entries of this file like this: 我想写下snapshotname以及要写入另一个文件的createtime,这个文件的所有条目都是这样的:
SnapshotName : testdatabase-05-07-15-00-00
CreateTime : 05/07/2015 00:00:00 AM
SnapshotName : testdb-10-07-15-00-00
CreateTime : 10/07/2015 00:00:00 AM
I am able to write snapshotname of all the entries, but not createtime. 我能够写出所有条目的快照名称,但不能写入创建时间。 What I've tried so far is:
到目前为止我尝试过的是:
Get-Content "path\file.txt" | Where-Object {$_ -match 'SnapshotName'} | Set-Content "path\file2.txt"
I tried like adding another Where-Object to the above code like this, but failed to achieve the target. 我尝试像上面的代码一样添加另一个Where-Object,但是没能达到目标。
Get-Content "path\file.txt" | Where-Object {$_ -match 'SnapshotName'} | Where-Object {$_ -match 'CreateTime'} | Set-Content "path\file2.txt"
I know I am missing something small. 我知道我错过了一些小事。 Can someone please help me how can I achieve what I said above.?
有人可以帮助我,我怎样才能实现我上面所说的。 Any response would be really appreciated.
任何回应都会非常感激。
使用select-string
代码更少:
get-content "path\file.txt" | Select-String "^(SnapshotName|CreateTime)" | out-file "path\file2.txt"
After the first Where-Object {$_ -match 'SnapshotName'} you only get lines with SnapshotName so you cannot use another Where-Object because it will search you previous output. 在第一个Where-Object {$ _ -match'SnapshotName'}之后,您只能获得具有SnapshotName的行,因此您无法使用另一个Where-Object,因为它将搜索您之前的输出。 Use this code:
使用此代码:
Get-Content "path\file.txt" | Where-Object { $_ -match 'SnapshotName' -or $_ -match 'CreateTime' } | Set-Content "path\file2.txt"
Here is an an other approach using a switch
statement and regex 这是另一种使用
switch
语句和regex的方法
gc c:\temp\file.txt |%{
switch -regex ($_){
'(SnapshotName.*)' {$Matches[1] |out-file c:\temp\resu.txt -append}
'(CreateTime.*)'{$Matches[1] |out-file c:\temp\resu.txt -append}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.