Sunday, January 7, 2007

Process-File function

Some time ago while scripting (either bash or PowerShell) I've found myself using some pattern too often. It can be expressed as

  1. take a file;
  2. process every line in it;
  3. 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:

/\/\o\/\/ said...

Nice one, very handy I added it to my profile.

thanks

Greetings /\/\o\/\/