Reputation: 923
We have multiple text files in a folder that needs editing. The text files are Multi-Stage Azure Pipelines as code (.yaml) for Azure DevOps, that we need to update. We have specific line numbers that need to be cut, for example we need to cut out lines 54-68 from 30 files, but keep the rest of the code. An example of such lines:
- stage: DeployWebApps
variables:
- group: Environment1
jobs:
- job: DeployWebApps
pool:
vmImage: 'windows-latest'
steps:
- task: AzureFileCopy@3
displayName: 'Copy ARM Template'
inputs:
SourcePath: 'DevOps\IaC\WebApps.json'
azureSubscription: Development Subscription Service Connection'
Destination: 'AzureBlob'
storage: 'xxx'
ContainerName: 'armtemplates'
outputStorageUri: 'artifactsLocation'
outputStorageContainerSasToken: 'artifactsLocationSasToken'
sasTokenTimeOutInMinutes: '240'
We would like to use the approach I described because line 56:
- group: Environment1
is different in each file while the rest of the lines are the same. Regex seem to be overkill that is more difficult to write than PowerShell for such case and doesn’t solve the problem of replacing lines in multiple files.
The best approach I found is in an answer here Powershell remove a range of lines from a text file
If the content you want is always on the first 4 lines you can just do this:
(Get-Content C:\file.txt)[0..3] | set-content C:\outfile.txt
This script removes everything except lines 1-4. How can I remove only lines 54-68 instead?
Upvotes: 0
Views: 3689
Reputation: 27423
Here's an odd solution that uses the hidden readcount property returned by get-content.
# get-content c:\file.txt | select *
get-content c:\file.txt | where readcount -notin (54..68) |
set-content c:\outfile.txt
Upvotes: 0
Reputation: 25001
In PowerShell Core (v7+), Select-Object
has a -SkipIndex
parameter that allows skipping multiple lines using the pipeline.
Get-Content -Path file.txt | Select-Object -SkipIndex (53..67) |
Set-Content output.txt
Note that -SkipIndex
skips the actual index number (starts at 0
) rather than the number of lines as required by -Skip
.
Upvotes: 1
Reputation: 763
This can be done as follow:
[string[]]$array = Get-Content -Path C:\file.txt
$array[0..52] + $array[68 ..($array.length -1)] | Set-Content C:\outfile.txt
Upvotes: 3