- take a file;
- process every line in it;
- save file back.
E.g. `sed -i' provides this kind of functionality. This was kind of boring, because you can't just write "cat file.txt | do-something > file.txt", and if you really could, this was too long anyway. So I wrote function which does just that -- takes file, processes it with some code (specified as an argument), and writes it back. Here it goes:
function Process-File([scriptblock]$script, $filename) {
$local:temp = [System.IO.Path]::GetTempFileName()
Get-Content $filename | Foreach $script > $local:temp
Move-Item -force $local:temp $filename
}
Here some testing code:
PS C:\Documents and Settings\andrey> cat test.txt
PS C:\Documents and Settings\andrey> echo "abcabc" > test.txt
PS C:\Documents and Settings\andrey> cat test.txt
abcabc
PS C:\Documents and Settings\andrey> Process-File { $_ -replace 'a','b' } test.txt
PS C:\Documents and Settings\andrey> cat test.txt
bbcbbc
PS C:\Documents and Settings\andrey>
PowerShell is just wonderfull.
1 comment:
Nice one, very handy I added it to my profile.
thanks
Greetings /\/\o\/\/
Post a Comment