Advertisement
Dennisaa

Return a subset of a file

Feb 18th, 2014
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .Synopsis
  3.    Given a file, return a subset of that file.
  4. .Description
  5.    Restriction is by line number. At least 2 arguments are required:
  6.    - the file name, including path, and
  7.    - the last line to be returned. So if the file contains 1000 lines, and the second
  8.      argument is 500 (and there is no 3rd argument), then lines 1-500 will be returned
  9.    If the argument count is 3, then for simplicity, this last argument is taken to be
  10.    the FIRST line to include. The example below shows how this plays.
  11.    Generate a test file for the examples below thus:
  12.    1..1000 > d:\scratch\1000_line_file.txt
  13. .Example
  14.    This will return lines 1-500 from the original
  15.    "d:\scratch\1000_line_file.txt" | Reduce-File 500
  16. .Example
  17.    This will return lines 3-500 from the original
  18.    "d:\scratch\1000_line_file.txt" | Reduce-File 500 3
  19. .Example
  20.    This will return lines 3-1000 from the original, because 1000 is the maximum: no exception is thrown:
  21.    "d:\scratch\1000_line_file.txt" | Reduce-File 1500 3
  22. .Example
  23.     This will write the output to a further file. Note that it is not possible in this function to write back to the same file - a separate function should manage that.
  24.    "d:\scratch\1000_line_file.txt" | Reduce-File 1500 3 | Out-File .\x.txt
  25. #>
  26. function Reduce-File
  27. {
  28.     Param
  29.     (
  30.         [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
  31.         [string]
  32.         $FileNameWithPath,
  33.         [Parameter(Mandatory=$true, Position=1)]
  34.         [int]
  35.         $LastLineNumberToInclude,
  36.         [Parameter(Mandatory=$false, Position=2)]
  37.         [int]
  38.         $FirstLineNumberToInclude
  39.     )
  40.  
  41.     Process {
  42.         $lines = get-content $FileNameWithPath
  43.         if ($LastLineNumberToInclude -gt $lines.Count) {
  44.             $LastLineNumberToInclude = $lines.Count
  45.         }
  46.  
  47.         $restrictedFile = $lines |
  48.             select -First $LastLineNumberToInclude |
  49.                 select -Last $($LastLineNumberToInclude - ($FirstLineNumberToInclude - 1))
  50.         $restrictedFile
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement