Question

Can anybody help me how to use this bash filter : fold -w1 in powershell? So i need to write a string's characters in new lines. "example blabla"
e
x
a
m
p
l
e

b
l
a
b
l
a

Was it helpful?

Solution 2

Another option:

$string = "example blabla"
$string -replace '(.)', "`$1`n"

You could also do the replacement like this:

$string -replace '', "`n"

but that way the output will have a leading newline.

By wrapping the replacement in a function like this:

function Fold {
  param(
    [CmdletBinding()]

    [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true)]
    [string]$String,

    [Parameter()]
    [alias('w')]
    $Width=80
  )

  $String -replace "(.{$Width})", "`$1`n"
}

you could use it in (more or less) the same way as the shell utility:

PS C:\> Fold -w:1 'example blabla'
e
x
a
m
p
l
e

f
o
o

PS C:\> 'example blabla' | Fold -w:5
examp
le bl
abla

OTHER TIPS

Casting to [char[]] will work, but that won't actually get the result newline separated. Running the result through Out-String is an easy way to do that:

$string= "Example blabla"

[Char[]]$string | Out-String

One way to do it:

$string= "Example blabla"

[Char[]]$string

Other examples:

"Example blabla".ToChararray()

[char[]]"Example blabla"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top