I'm manipulating a test where I use multiple .replace
commands to format the text.
For example
$str="hello%worldZZZniceZZZtoZZZmeet"
$str.Replace("%","`n").replace("ZZZ","`n")
Output in the console is good but I need to iterate each line.
problem is $str.count = 1
meaning powershell looks at this string still as one line even when it shows up good in the console.
any idea?
Edit:
If I output the string to file and then read the file it does read with new lines but there's a better way I'm sure instead of outputting to file and then reading it back again
CodePudding user response:
Sounds like you're looking to split the string and get an array as result:
$str = "hello%worldZZZniceZZZtoZZZmeet"
$str -split "%|ZZZ"
($str -split "%|ZZZ").count # => 5
Since the operator is regex compatible you can use "%|ZZZ"
(split on %
or ZZZ
).
CodePudding user response:
Strings in .NET are immutable, meaning they always return a new string instead of modifying the current string, therefore after you run $str.Replace("%","`n").replace("ZZZ","`n")
the original string is still unchanged. You need to store the result to a new variable if you want to deal with it
PS C:\Users> $newstr = $str.Replace("%","`n").replace("ZZZ","`n")
PS C:\Users> $newstr
hello
world
nice
to
meet
PS C:\Users> $str
hello%worldZZZniceZZZtoZZZmeet
But even then $newstr
is still a string which doesn't have any count
method. I don't know what you want to do with count
. If you want to get the number of lines in the variable then just use Measure-Object
PS C:\Users> $newstr | Measure-Object -Line
Lines Words Characters Property
----- ----- ---------- --------
5
PS C:\User> ($newstr | Measure-Object -Line).Lines
5