PowerShell_unix PowerShell is definitely gaining momentum in the windows scripting world but I still hear folks wanting to rely on Unix based tools to get their job done.  In this series of posts I’m going to look at converting some of the more popular Unix based tools to PowerShell.

fold

The Unix “fold” command will take as input a list of files and wrap each input line to fit within a specified width.  By default, fold breaks lines wider than 80 columns and the output is split into as many lines as necessary.

I’ve included the following runtime arguments in my implementation:

Unix PowerShell Description
-s -spaces Break at spaces when possible.
-w -width Use WIDTH columns instead of 80.

The code is fairly straightforward.  Each file is iterated upon and then for each file, each line is processed.  if the width is less than or equal to the specified width, it is printed to the console.  If it is greater than the width, if “spaces” is not specified, it is broken in chunks of WIDTH characters.  If “spaces” is specified, then if the character at the WIDTH marker is not a space character and the following character is not either, a reverse search is performed back to the beginning of the line to search for the first space character.  If one is found, the line up to that point is sent to the output.