What is the fastest/easiest way to increase a number in a string variable in Powershell? - powershell

I have the following Powershell variable
$var = "AB-0045"
I would like to increase the number in the string to become "AB-0046".
I can do:
$newNumber = [int]$var.Substring($var.length -4,4) + 1
Which will give me the desired number 46, but then I have to append that 46 as a string to a new string "AB-00".
Is there a better way to do that?

Now that you have the integer, you'll have to convert back to string formatted in the way you'd like and concatenate.
I'd recommend adding to "AB-" rather than "AB-00" in case your number goes over 100.
To pad leading zeros, you can use the -f operator.
e.g. "{0:d4}" -f 45
You'll still need to get the integer first (45 in the example) from your original string.

I tested with regex class Replace() method and string class Split() method with string formatter. Split() seems faster provided your string is always in the same format. The Replace() method does not care what happens before the last 4 numbers:
# Replace Method
[regex]::Replace($var,'\d{4}$',{([int]$args[0].Value+1).ToString('0000')})
# Split method
$a,[int]$b = $var.split('-'); "{0}-{1:0000}" -f $a,++$b

Related

Trying to convert the number numeric value in this string to a percent. Is there any easy way to do this in powershell?

Trying to convert the number numeric value in this string to a percent. Is there any easy way to do this in powershell?
"Percentage of records ","0.02"
So, the output would look like :
Percentage of records , 2%
Thanks in advance for any suggestions you can provide.
Yes, you can convert the string to a float data type (single, double, decimal), and then convert it back using a format string, like so:
"Percentage of records ", ([double]'0.02').ToString('P0')
And if you want it to output in a single line, you could use:
"Percentage of records: $(([double]'0.02').ToString('P0'))"
Explanation:
Convert your string to a float datatype: [double]'0.02'
Convert that float back into a string: .ToString()
But we want to format it as a percentage, so we supply P0 as a parameter.
i. P - means to format the value as a percentage, this performs the N * 100 operation for you and then adds on the percent sign
ii. 0 - controls the number of decimal places to show. In your case, you want to show zero decimal places.
Note: The percentage format string will round your value to the nearest decimal that you specify.
Example:
0.021.ToString('P0')
# returns 2%
0.025.ToString('P0')
# returns 3%
As #mklement0 pointed out in the comments. I hadn't considered that your sample may be a single string, like:
'"Percentage of records ","0.02"'
I assumed it was two strings, which you separated with a comma.
In the event it is a single string, then you need to extract the number to use it. Once you have isolated the number, then you can use my advice above:
$yourString = '"Percentage of records ","0.02"'
# probably the more "proper" way
$pctValue = ($yourString -split ',' -replace '"')[1]
# or
# a hacky way I just thought of that happens to work in this scenario
$pctValue = (iex $yourString)[1]
Explanation of first example:
-split ',' - Take the string, and break it out into multiple strings, separating them by comma
-replace '"','' - Replace all instances of " with blank. The second parameter is optional since you are removing. Could be written as -replace '"'
(...)[1] - This is saying to take the SECOND string that it returned (starts at zero). In this case it would be your 0.02 value.
Explanation of second example (this is a bit of a hack, but thought it would be fun to include anyway):
iex - alias for Invoke-Expression - it's telling powershell to run whatever is inside of the string verbatim. So it's the equivalent of typing "Percentage of records ","0.02" into powershell and hitting enter. Which in PowerShell terms, that is the equivalent of passing it a list of strings.
Use -f (format operator) in powerhsell for build your string :
"Percentage of records, {0:0%} " -f 0.02
or in percentage :
"Percentage of records, {0:P0} " -f 0.02

How do I parse out a number from this returned XML string in python?

I have the following string:
{\"Id\":\"135\",\"Type\":0}
The number in the Id field will vary, but will always be an integer with no comma separator. I'm not sure how to get just that value from that string given that it's string data type and not real "XML". I was toying with the replace() function, but the special characters are making it more complex than it seems it needs to be.
is there a way to convert that to XML or something that I can reference the Id value directly?
Maybe use a regular expression, e.g.
import re
txt = "{\"Id\":\"135\",\"Type\":0}"
x = re.search('"Id":"([0-9]+)"', txt)
if x:
print(x.group(1))
gives
135
It is assumed here that the ids are numeric and consist of at least one digit.
Non-regex answer as you asked
\" is an escape sequence in python.
So if {\"Id\":\"135\",\"Type\":0} is a raw string and if you put it into a python variable like
a = '{\"Id\":\"135\",\"Type\":0}'
gives
>>> a
'{"Id":"135","Type":0}'
OR
If the above string is python string which has \" which is already escaped, then do a.replace("\\","") which will give you the string without \.
Now just load this string into a dict and access element Id like below.
import json
d = json.loads(a)
d['Id']
Output :
135

Function to split string in matlab and return second number

I have a string and I need two characters to be returned.
I tried with strsplit but the delimiter must be a string and I don't have any delimiters in my string. Instead, I always want to get the second number in my string. The number is always 2 digits.
Example: 001a02.jpg I use the fileparts function to delete the extension of the image (jpg), so I get this string: 001a02
The expected return value is 02
Another example: 001A43a . Return values: 43
Another one: 002A12. Return values: 12
All the filenames are in a matrix 1002x1. Maybe I can use textscan but in the second example, it gives "43a" as a result.
(Just so this question doesn't remain unanswered, here's a possible approach: )
One way to go about this uses splitting with regular expressions (MATLAB's strsplit which you mentioned):
str = '001a02.jpg';
C = strsplit(str,'[a-zA-Z.]','DelimiterType','RegularExpression');
Results in:
C =
'001' '02' ''
In older versions of MATLAB, before strsplit was introduced, similar functionality was achieved using regexp(...,'split').
If you want to learn more about regular expressions (abbreviated as "regex" or "regexp"), there are many online resources (JGI..)
In your case, if you only need to take the 5th and 6th characters from the string you could use:
D = str(5:6);
... and if you want to convert those into numbers you could use:
E = str2double(str(5:6));
If your number is always at a certain position in the string, you can simply index this position.
In the examples you gave, the number is always the 5th and 6th characters in the string.
filename = '002A12';
num = str2num(filename(5:6));
Otherwise, if the formating is more complex, you may want to use a regular expression. There is a similar question matlab - extracting numbers from (odd) string. Modifying the code found there you can do the following
all_num = regexp(filename, '\d+', 'match'); %Find all numbers in the filename
num = str2num(all_num{2}) %Convert second number from str

PARI:similar function like Integer.parseInt()

I want to convert the text hello to ascii decimal in PARI/GP. After that I will
concatenate the values.
I initialize a Vecsmall(hello), after that I run a loop to concatenate the ascii decimal values,
I want to use this concatenated value to * by certain values. The value is now in String type, In Java, there is a Integer.parseInt() to convert the string to int. I wonder if there is a similar function in PARI/GP?
v=Vecsmall("hello");'
for (i = 1, length(v), text=Str(text,v[i]););
//is there any similar function like Integer.praseInt(text) in PARI?
You can use eval
eval(text)
or else a combination of Vecsmall and fromdigits which is faster:
fromdigits(apply(n->n-49, Vec(text)))

Powershell - Capture text in a var from a specific character

I want to grab the first char of a var string and the first char of the following caracter
Example:
$var1 = "Jean-Martin"
I want a way to grab the first letter "J" then I want to take the first char following the "-" (dash) which is "M".
Something like this?
$initial1 = $var1[0]
$initial2 = $var1.Split('-')[1][0]
Strings in Powershell use the System.String class from the .Net framework. As such, they are indexable to retrieve individual characters and have many methods available such as the Split method used above.
See the documentation here.
$var1 = "Jean-Martin"
To get the first character:
$var1[0]
To get the first character after the dash:
$characterToSeek = '-'
$var1[$var1.IndexOf($characterToSeek)+1]
Another option using regex:
PS> $var1 -replace '^(.)[^-]+-(.).+$','$1$2'
JM