开发者

Splitting one file into many with Powershell

I have a file called one_to_many.txt. In the file is the data:

a,aaa
b,bbb
c,ccc

I want to use powershell to create 3 files a.txt, b.txt and c.txt

File a.txt to contain d开发者_如何学运维ata "aaa", b to contain "bbb ...

I'm new to Powershell and can't work out how to do it. Thanks.


One possible solution:

Get-Content one_to_many.txt | Foreach-Object {
  $fileName, $content = $_ -split ','
  $content | Set-Content "$fileName.txt"
}

Get-Content reads the file and returns lines, one by one. Each line is piped to Foreach-Object where it can be accessed as $_.

You need to split the line by comma, so invoke operator -split which returns in this case array of 2 items. The assignment $filename, $content = .. causes that content of first item in array (from -split) is assigned to $filename and the rest to `$content.

Then simply store that content in the file via Set-Content

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜