Compare-Object and ignore white space

Welcome Forums General PowerShell Q&A Compare-Object and ignore white space

This topic contains 5 replies, has 5 voices, and was last updated by

2 years, 7 months ago.

  • Author
  • #26861

    Points: 0
    Rank: Member

    I'm trying to compare text files and all I care about is that the text within is the same, I don't care about white space or case sensitivity. Is there a way to do this with Compare-Object? I'm not seeing that there is, but if there is a way, please let me know...


  • #26863

    Points: 0
    Rank: Member

    Try this
    Compare-Object $(Get-Content c:\scripts\x.txt) $(Get-Content c:\scripts\y.txt)

    It will give you input like this if there is any changes.

    PS C:\> Compare-Object $(Get-Content c:\x1.txt) $(Get-Content c:\y1.txt)

    InputObject SideIndicator
    ———– ————-
    abcd =>
    abc <=

  • #26864

    Points: 0
    Rank: Member

    I tried this, I gives me all the white space differences..I'm trying to ignore white space

  • #26865

    Points: 38
    Rank: Member

    By default it's not case sensitive, if you wanted it to be you could specify the -CaseSensitive parameter.

    To ignore the whitespace, try using the trim() method.

    Compare-Object -ReferenceObject (get-content c:\ref.txt) -DifferenceObject (Get-Content c:\diff.txt).trim() -IncludeEqual

    Edit: I left the -IncludeEqual there just to prove my test files worked, you may want to remove it if you're looking for differences.

  • #26868

    Points: 428
    Helping Hand
    Rank: Contributor
    1. Get-Content creates a PSObject and basically creates each line as an individual object
    2. Compare-Object is going to compare each line of the object to see if it matches or one object contains a value the other does not with a side indicator

    If you want to compare these individual items, I would remove anything required prior to using Compare-Object. Maybe something like this:

    Get-Content Test.txt | foreach{ $_.Trim()
  • #42830

    Points: 57
    Rank: Member

    this worked for me:

    Compare-Object -ReferenceObject ((get-content c:\ref.txt).trim()) -DifferenceObject ((Get-Content c:\diff.txt).trim())

The topic ‘Compare-Object and ignore white space’ is closed to new replies.