Last active
April 7, 2016 13:13
-
-
Save thorade/b05f2da5a5d258253af0 to your computer and use it in GitHub Desktop.
PowerShell script that recursively scans all text files in a given directory and normalizes the end of file (by adding/removing newlines as appropriate)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This PowerShell Script will recursively scan all files in the given $scanDir | |
# and normalize the EOF by removing unnecessary whitespace and adding an EOL character to the last line of text | |
# Additionally, the script can normalize every EOL by trimming the trailing white space | |
cls; | |
$scanDir = "EnEffBIM-Framework" | |
$normalizeEOL = $TRUE | |
# get current directory, build scanPath | |
$curPath = Split-Path -Parent $MyInvocation.MyCommand.Path | |
$scanPath = $curPath + "\" + $scanDir | |
# use the same extensions for text files as specified in .gitattributes, in alphabetical order | |
$textFiles = Get-ChildItem -Recurse $scanPath -include *.h,*.mo,*.mos,*.py,*.order,*.txt -exclude *.csv,*.dat,*.md | |
# iterate through textFiles | |
ForEach ($file In $textFiles){ | |
# get content of each file | |
$fileContent = Get-Content $file | |
# count the lines | |
$fileLineNumber = $fileContent.Count | |
# Write-Host $file $fileLineNumber | |
if($fileLineNumber -le 0){ | |
#file is empty, do nothing | |
} | |
elseif($fileLineNumber -eq 1){ | |
# if file has one line only: trim it | |
$fileContent = $fileContent.trimEnd() | |
} | |
else{# file has more than 1 line | |
# if normalizeEOL, iterate through lines, trim each line | |
if($normalizeEOL){ | |
for($i=0; $i -lt $fileLineNumber; $i++){$fileContent[$i] = $fileContent[$i].trimEnd()} | |
} | |
# while last line is empty or contains white space only, decrease fileLineNumber and copy back fileContent without last line | |
while([string]::IsNullOrWhitespace($fileContent[$fileLineNumber-1])){ | |
$fileLineNumber-- | |
$fileContent = $fileContent[0..($fileLineNumber-1)] | |
} | |
} | |
# write back modified fileContent to file | |
Set-Content $file $fileContent | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script needs PowerShell Version 3.0 or newer
Print your PowerShell version using
$PSVersionTable