Home > Enterprise >  Format text with powershell and make a new file with new lines
Format text with powershell and make a new file with new lines

Time:12-25

I have some text inside album.txt like

some text1 beta glhjkj
gjkkj beta jjkgj jkj
ljj kgj jkg
gjkj bj beta jkgj

I want to get a formatted text in a second album2.txt in this way

beta glhjkj
beta jjkgj jkj 
beta jkgj

only rows that starts with beta are allowed

I try to test this .ps1 script from C:\temp but doesn't work

# Specifies that this is a PowerShell script
# and that the output data is in text format

[Console ]:: OutputEncoding = [ System.Text.Encoding ]:: UTF8

# Read the contents of the "album.txt" file

$lines = Get-Content .\album.txt

# Change the format of lines starting with "beta" by adding a newline at the end

$formattedLines = $lines | ForEach-Object {
    if ($_ -match '^beta') {
        "$_`n"
    }
}

# Overwrite the contents in the "album2.txt" file with the formatted lines

$formattedLines | Set-Content .\album2.txt

album.txt file is also inside C:\temp.
When I try to run this code nothing happens.

CodePudding user response:

Okay, there is a simple enough way to do this.

Consider this code:

$contents = Get-Content .\album.txt
$filtered = $contents | Where-Object { $_ -match "^beta" }
Set-Content -Path .\album2.txt -Value $filtered

The Where-Object filters the contents of the album.txt file and only include lines that start with "beta".

Now, if you want to add new lines in between the filtered lines, then instead of Set-Content you can use :

$filtered | Out-File -FilePath .\album2.txt -Append -NoClobber

CodePudding user response:

You could use a switch to read your file and match those lines having beta and everything after that word:

& {
    switch -Regex -File .\album.txt {
        '\bbeta\b.*' { $Matches[0] }
    }
} | Set-Content .\album2.txt

See https://regex101.com/r/qJRiP6/1 for the regex details.

CodePudding user response:

I test user3520363 and Santiago code and this solution is good about regex implementation

$contents = Get-Content .\album.txt
$filtered = $contents | Where-Object { $_ -match "\bbeta\s (.*)" } | ForEach-Object { "beta $($Matches[1])" }
Set-Content -Path .\album2.txt -Value $filtered
  • Related