1

I have written a following script to sort file content based on some column.

$lines = Get-Content $inputFile

foreach($line in $lines){
    if($line.startsWith('*') -or $line.startsWith('-')){
        continue
    }
    if(($line -eq $lines[0])  -or ($line -eq $lines[1]) -or ($line -eq $lines[2])){
        Sort-Object { $line.Substring(70,9) } | set-content $outputFile
    }
}

input file content:

 ...header row...
 ...header row...
 ...header row...
        4
        2
        1
 ....trailor.....

Desired Output:

 ...header row...
 ...header row...
 ...header row...
        1
        2
        3
 ....trailor.....

In my input file, I have first three lines as header and Lat line as trailer. I want to skip these lines while sorting. I tried to use above script. But it's not skipping those lines. Can someone correct me for this?

1 Answer 1

2

If you always want to skip the first three and last one line, you could also adopt your foreach loop:

foreach ($line in $lines[3 .. ($lines.Count -2)])
{
    Write-Host $line
}

Your foreach loop will now starts on the forth element and runs until the line before the last line.

Edit: Here a solution for your example where I create a new array and just sort the specific lines using the Sort-Object cmdlet (alias sort) and finally set the new content using the Set-Content cmdlet:

$lines = Get-Content $inputFile
@($lines[0 .. 2], ($lines[3 .. ($lines.Count -2)] | Sort-Object -Descending), $lines[-1]) | Set-Content $outputFile
Sign up to request clarification or add additional context in comments.

4 Comments

Hi..Thanks for your response! Could you please give command with Sort-Objet, because in my case alos I am skipping but it's not working. SO I want to try your command
You have to share us an example and tell us the desired output. Otherwise, im not able to help you.
Yes, I added a 2-liner solution that does exactly what you want.
You are welcome. I removed the $line.Substring from your edit since that won't work here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.