CleanCode logo
sitemap
SEARCH:

CleanCode PowerShell Libraries v1.2.08 API: CleanCode » FileTools » Select-StringAligned

Select-StringAligned

NAME

Select-StringAligned

SYNOPSIS

Finds text in strings and files and makes the output aligned rather than ragged based on file name lengths.

SYNTAX

Select-StringAligned [-Path] <Object[]> [-Pattern] <String> [-Context <Int32[]>] [-NameWidth <Int32>] [-NumberWidth <Int32>] [-CaseSensitive] [-List] [-PassThru] [<CommonParameters>]

DESCRIPTION

The Select-StringAligned cmdlet searches for text and text patterns in input strings and files similar to its counterpart, Select-String. It differs in two main features: It aligns the lines of matched text (by putting the file name and line number in fixed width fields) and it highlights the matched text.

Compare this output from Select-StringAligned:

        Assertion\Assertion.Tests.ps1           : 17: # the Mozilla License Version
        FileTools\ConvertFrom-Text.ps1          : 17: # the Mozilla License Version
        FileTools\ConvertFrom-Text.Tests.ps1    : 17: # the Mozilla License Version
        FileTools\FileTree.ps1                  : 17: # the Mozilla License Version

with this output from Select-String:

        Assertion\Assertion.Tests.ps1:17:# the Mozilla License Version
        FileTools\ConvertFrom-Text.ps1:17:# the Mozilla License Version
        FileTools\ConvertFrom-Text.Tests.ps1:17:# the Mozilla License Version
        FileTools\FileTree.ps1:17:# the Mozilla License Version

Select-StringAligned is line-oriented. By default, it highlights all matches in each line and, for each line displays the file name, line number, and text of the line with each match highlighted. Select-StringAligned uses regular expression matching.

Select-StringAligned implements some of Select-String's options allowing you to display lines before and after each matched line, or display just the first match in each file. It also has several custom parameters allowing you to adjust the fixed width of the file name field and the line number field.

Highlighting is one of the two main benefits of Select-StringAligned. However, be aware that highlighted output is not pipelineable! You may, however, send the aligned output into a pipeline--without the highlight--with the -PassThru option.

Another enhancement of Select-StringAligned is that it reports relative paths whenever possible whereas Select-String always reports absolute paths, making output lines always lengthy. Thus, instead of
        C:\Users\me\some\lengthy\pass\here\that\just\goes\on\and\on\file.cs: 132 ...
you might see
        .\file.cs: 132 ...
or
        ..\..\..\and\on\file.cs: 132 ...
(Note that it is rather unwieldy to go up more than three levels (..\..\..), though, so it will revert to absolute paths at that point.)

If you do a lot of searching, it is convenient to have a helper alias with the options you prefer. Here is an example that you might put in your PowerShell profile named after the common Unix/Linux grep:

        function grep($txtpat, $filepat="*") {
            Get-ChildItem . -Exclude *.exe,*.obj,*.suo,*.user -Include $filepat -File -Recurse |
            Select-StringAligned $txtpat -NameWidth 40 -Context 2,3
        }

What I use is very similar, except that I use my own extension to Get-ChildItem that allows pruning whole trees:
        Get-EnhancedChildItem . -ExcludeTree .svn,bin,obj -exclude *.exe,*.obj,*.suo,*.user ...

Get-EnhancedChildItem is also available in this CleanCode library.

PARAMETERS

-Path <Object[]>
        Specifies the path to the files to be searched. Wildcards are permitted.
        The default location is the local directory.

        Specify files in the directory, such as "log1.txt", "*.doc", or "*.*".
        If you specify only a directory, the command fails.

        Required?                    true
        Position?                    2
        Default value                
        Accept pipeline input?       true (ByValue, ByPropertyName)
        Accept wildcard characters?  true

-Pattern <String>
        Specifies the text to find as a regular expression.
        To learn about regular expressions, see about_Regular_Expressions.

        Required?                    true
        Position?                    1
        Default value                
        Accept pipeline input?       false
        Accept wildcard characters?  false

-Context <Int32[]>
        Captures the specified number of lines before and after the line with the match.
        This allows you to view the match in context.

        If you enter one number as the value of this parameter, that number determines
        the number of lines captured before and after the match. If you enter two numbers
        as the value, the first number determines the number of lines before the match
        and the second number determines the number of lines after the match.

        In the default display, the actual matched lines have the search target
        highlighted. Unmarked lines are the context.

        Required?                    false
        Position?                    named
        Default value                @(0)
        Accept pipeline input?       false
        Accept wildcard characters?  false

-NameWidth <Int32>
        Specifies the fixed width of the file name portion of the output.

        Required?                    false
        Position?                    named
        Default value                35
        Accept pipeline input?       false
        Accept wildcard characters?  false

-NumberWidth <Int32>
        Specifies the fixed width of the line number portion of the output.

        Required?                    false
        Position?                    named
        Default value                5
        Accept pipeline input?       false
        Accept wildcard characters?  false

-CaseSensitive [<SwitchParameter>]
        Makes matches case-sensitive. By default, matches are not case-sensitive.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?       false
        Accept wildcard characters?  false

-List [<SwitchParameter>]
        Returns only the first match in each input file.
        By default, all matches are reported.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?       false
        Accept wildcard characters?  false

-PassThru [<SwitchParameter>]
        Sends the output to stdout rather than the PowerShell host console.
        This allows the output to be piped to another command
        but also disables match highlighting as a consequence.

        Required?                    false
        Position?                    named
        Default value                False
        Accept pipeline input?       false
        Accept wildcard characters?  false

<CommonParameters>
        This cmdlet supports the common parameters: Verbose, Debug,
        ErrorAction, ErrorVariable, WarningAction, WarningVariable,
        OutBuffer and OutVariable. For more information, see 
        about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). 

INPUTS

You can pipe any object that has a ToString method to Select-String.

OUTPUTS

Array of System.String objects (with -PassThru) or none (default).

NOTES



        This function is part of the CleanCode toolbox
        from http://cleancode.sourceforge.net/.

        Since CleanCode 1.2.03.

EXAMPLES


-------------------------- EXAMPLE 1 --------------------------

PS>Select-StringAligned -Path *.ps1 -Pattern ^function

Search ps1 files in the current directory only and find lines beginning with "function". Example output:
        SvnInfo.ps1                        :  193: function Get-SvnInfo(
        SvnInfo.ps1                        :  239: function Match-Expression($string, $regex)
        SvnInfo.ps1                        :  248: function ConvertTo-HashTable()
        SvnInfo.Tests.ps1                  :   44: function Get-PropertyCount($results)
        SvnKeywords.ps1                    :  222: function Measure-SvnKeywords(
        SvnKeywords.ps1                    :  318: function Progress($activity)
        SvnKeywords.ps1                    :  324: function GetExtensionsEnabledInConfig()

-------------------------- EXAMPLE 2 --------------------------

PS>Get-ChildItem -Recurse *.ps1 | Select-StringAligned -Pattern ^function

Search ps1 files in the current directory and its descendants and find lines beginning with "function". Example output:
        SqlTools\DefaultContext.ps1        :  249: function Invoke-InferredSqlcmd()
        SqlTools\Out-DataTable.ps1         :   62: function Out-DataTable
        SqlTools\Out-DataTable.ps1         :  136: function Get-Type
        SqlTools\Out-SqlTable.ps1          :  154: function Out-SqlTable
        SqlTools\Write-DataTable.ps1       :  104: function Write-DataTable
        SvnTools\SvnInfo.ps1               :  193: function Get-SvnInfo(
        SvnTools\SvnInfo.ps1               :  239: function Match-Expression($string, $regex)
        SvnTools\SvnInfo.ps1               :  248: function ConvertTo-HashTable()
        SvnTools\SvnInfo.Tests.ps1         :   44: function Get-PropertyCount($results)
        SvnTools\SvnKeywords.ps1           :  222: function Measure-SvnKeywords(
        SvnTools\SvnKeywords.ps1           :  318: function Progress($activity)
        SvnTools\SvnKeywords.ps1           :  324: function GetExtensionsEnabledInConfig()

-------------------------- EXAMPLE 3 --------------------------

PS>Get-ChildItem -Recurse | Select-StringAligned '<summary>' -Context 0,1

Search all files in the tree rooted at the current directory, find instances of "<summary>" documentation tags and print both that line and one line immediately following it. Note that as soon as the context widens the viewport to more than one line, you also get "---" separators between matches. Example output:
        Forms\WindowRestorer.cs    :  341:         /// <summary>
        Forms\WindowRestorer.cs    :  342:         /// Sets the location of a sub-window relative to its base form
        ---
        Forms\WindowRestorer.cs    :  358:         /// <summary>
        Forms\WindowRestorer.cs    :  359:         /// Maximizes a form over multiple monitors.
        ---
        IO\Comparators.cs          :   48:      /// <summary>
        IO\Comparators.cs          :   49:      /// An <see cref="IComparer"/> for sorting files by ascending date.
        ---
        IO\Comparators.cs          :   69:              /// <summary>
        IO\Comparators.cs          :   70:              /// Compares two <see cref="FileSystemInfo"/> objects
        ---
        IO\Comparators.cs          :  103:      /// <summary>
        IO\Comparators.cs          :  104:      /// An <see cref="IComparer"/> for sorting files by descending date.
        ---

-------------------------- EXAMPLE 4 --------------------------

PS>Get-ChildItem -Recurse | Select-StringAligned -Pattern '<summary>' -Context 0,1 -PassThru | Select-String -Pattern '<summary>','---' -NotMatch

Search all files in the tree rooted at the current directory, find instances of "<summary>" documentation tags and include the line immediately following it, then filter that again to report only that line immediately following. That is, filter out the "<summary>" match anchor and the "---" occurrence separators. Note that in order to pipe the output of Select-StringAligned you must include the -PassThru parameter. That makes the output pipelineable (with the side effect of losing the color-coding).

Example output:
        Forms\WindowRestorer.cs    :  342:         /// Sets the location of a sub-window relative to its base form
        Forms\WindowRestorer.cs    :  359:         /// Maximizes a form over multiple monitors.
        IO\Comparators.cs          :   49:      /// An <see cref="IComparer"/> for sorting files by ascending date.
        IO\Comparators.cs          :   70:              /// Compares two <see cref="FileSystemInfo"/> objects
        IO\Comparators.cs          :  104:      /// An <see cref="IComparer"/> for sorting files by descending date.

RELATED LINKS

This documentation set was created with CleanCode's DocTreeGenerator.

Valid XHTML 1.0!Valid CSS!Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads
Copyright © 2001-2015 Michael Sorens • Contact usPrivacy Policy
Usage governed by Mozilla Public License 1.1 and CleanCode Courtesy License
CleanCode -- The Website for Clean DesignRevised 2015.12.16