Echo string showing escaped characters - powershell

Is there a way to echo a string showing the escaped characters in powershell? I am looking for something similar to the repr function in python. I would like to use this for debugging.
For example:
>>$var="abc`ndef"
>>echo $var
Output:
abc
def
Desired output:
"abc`ndef"
or
abc`ndef

This will unescape the ` replacing it with a \
Hence the -replace at the end:
$var="abc`ndef"
$var = [System.Text.RegularExpressions.Regex]::Escape($var) -replace '\\','`'
echo $var
Output:
abc`ndef

I know this is not what you want, but will work fine :)
function Get-EscapedString([string] $String) {
$escape = #{
"`0"='`0';
"`a"='`a';
"`b"='`b';
"`f"='`f';
"`n"='`n';
"`r"='`r';
"`t"='`t';
"`v"='`v'
}
$str = $String
foreach ($char in $escape.Keys) {
$str = $str -replace $char, $escape[$char]
}
$str
}

Surround the string with single-quotes and the escape sequences won't be interpreted:
"abc`ndef"
outputs
abc
def
but
'abc`ndef'
outputs
abc`ndef

Related

How to cut specific characters in a string and save it to a new file?

I have a string, and I want to cut some characters and store it to a new file.
I tried this code, but it still error.
$a = ";Code=NB"
$b = $a -split "="
$b[1]
$Save = "[AGM]", "CR=JP", "LOC= $b[1]"| Out-File "C:\Users\Out.txt"
Try something like this:
$a = ";Code=NB"
$null, $b, $null = $a -split '=', 3
$b
$Save = "[AGM]", "CR=JP", "LOC= $b"| Out-File "C:\Users\Out.txt"
Something that would be easier to maintain would be this:
#Words to remove from string
$wordsToCut = "This","is"
#Phrase to remove words from
$phrase = "This is a test"
#Running through all words in words to remove
foreach ($word in $wordsToCut){
#Replace current word with nothing
$phrase = $phrase.Replace($word,"")
}
#Output end result
Write-Host $phrase
You would also use trim to remove any leading or trailing spaces. The above code outputs:
a test

Remove duplicate curly braces from string

This one is how I build the string and assign that to a variable:
$package = $package+$component+"=[{"+$componentField+":"+$componentValue+"}"
Write-Host $package
Output:
efc90fde-c75c-d5e5-bd3e-7f7ce358e2e2=[{{artifacturl:http://10.1.18.12:8088/job/Xyz/640/artifact/target/xyz.war}}
Expecting:
efc90fde-c75c-d5e5-bd3e-7f7ce358e2e2=[{artifacturl:http://10.1.18.12:8088/job/Xyz/640/artifact/target/xyz.war}
Just do:
$package = $package+$component+"=[{"+$componentField+":"+$componentValue+"}".Replace("{{", "{")..Replace("}}", "}")
BTW, this should also do the trick:
$package = $package+$component+ "=[$componentField:$componentValue"
You could also use a regex to replace the string:
$package -replace '({|})\1', '$1'
Demo.
However, I would suggest you to build the string using a format string:
$package = '{0}{1}=[{2}:{3}' -f $package, $component, $componentField, $componentValue

perl find and replace ../ and  

I am using Perl to replace all instances of
../../../../../../abc' and  
in a string with
/ and , respectively.
The method I am using looks like this:
sub encode
{
my $result = $_[0];
$result =~ s/..\/..\/..\/..\/..\/..\//\//g;
$result =~ s/ / /g;
return $result;
}
Is this correct?
Essentially, yes, although the first regex has to be written in a different way: because . matches any character, we have to escape it \. or put it in its own character class [.]. The first regex can also be written cleaner as
...;
$result =~ s{ (?: [.][.]/ ){6} }
{/}gx;
...;
We look for the literal pattern ../ repeated 6 times and then replace it. Because I use curly braces as a delimiter I don't have to escape the slash. Because I use the /x modifier I can have these spaces inside the regex improving readability.
Try this. It will print /foo bar/baz.
#!/usr/bin/perl -w
use strict;
my $result = "../../../../../../foo bar/baz";
#$result =~ s/(\.\.\/)+/\//g; #for any number of ../
$result =~ s/(\.\.\/){6}/\//g; #for 6 exactly
$result =~ s/ / /g;
print $result . "\n";
you forgot the abc, i think:
sub encode
{
my $result = $_[0];
$result =~ s/(?:..\/){6}abc/\//g;
$result =~ s/ / /g;
return $result;
}

Powershell - search for string, remove excess whitespace, print second field

I'm having a problem parsing some string data in powershell and need a little help. Basically I have an application command that doesn't output objects, rather string data.
a = is the item I'm searching for
b = is the actual ouput from the command
c = replaces all the excess whitespace with a single space
d = is supposed to take $c "hostOSVersion 8.0.2 7-Mode" and just print "8.0.2 7-Mode"
However, $d is not working it just prints the same value as $c. I'm a UNIX guy and this would be easy in one awk statement. If you know how to do this in one command that would be nice, or just tell me what's wrong with my $d syntax below.
$a = "hostOSVersion"
$b = "hostOSVersion 8.0.2 7-Mode"
$c = ($a -replace "\s+", " ").Split(" ")
$d = ($y -replace "$a ", "")
Well you might have to futz around with the exact pattern, but one way is with a regex:
$b = "hostOSVersion 8.0.2 7-Mode"
$b -match '(\d.*)'
$c = $matches[1]
If you really wanted to oneline it with -replace:
$($($b -replace $a, '') -replace '\s{2}', '').trim()
Your line
$c = ($a -replace "\s+", " ").Split(" ")
should reference the $b variable instead of $a
$c = ($b -replace "\s+", " ").Split(" ")
Then, you will notice the output of $d becomes
hostOSVersion
8.0.2
7-Mode
and a statement like $d[1..2] -join ' ' would produce 8.0.2 7-Mode

How to substitute arbitrary fixed strings in Perl

I want to replace a fixed string within another string using Perl. Both strings are contained in variables.
If it was impossible for the replaced string to contain any regex meta-characters, I could do something like this:
my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = 'lazy';
my $replace = 'drowsy';
$text =~ s/$search/$replace/;
Alas, I want this to work for arbitrary fixed strings. E.g., this should leave $text unchanged:
my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = 'dog.';
my $replace = 'donkey.';
$text =~ s/$search/$replace/;
Instead, this replaces dog! with donkey., since the dot matches the exclamation mark.
Assuming that the variable contents themselves are not hardcoded, e.g., they can come from a file or from the command line, is there a way to quote or otherwise markdown the contents of a variable so that they are not interpreted as a regular expression in such substitution operations?
Or is there a better way to handle fixed strings? Preferably something that would still allow me to use regex-like features such as anchors or back-references.
Run your $search through quotemeta:
my $text = 'The quick brown fox jumps over the lazy dog!';
my $search = quotemeta('dog.');
my $replace = 'donkey.';
$text =~ s/$search/$replace/;
This will unfortunately not allow you to use other regex features. If you have a select set of features you want to escape out, perhaps you can just run your $search through a first "cleaning" regex or function, something like:
my $search = 'dog.';
$search = clean($search);
sub clean {
my $str = shift;
$str =~ s/\./\\\./g;
return $str;
}
Wrap your search string with \Q...\E, which quotes any meta characters within.
$text =~ s/\Q$search\E/$replace/;
#Replace a string without using RegExp.
sub str_replace {
my $replace_this = shift;
my $with_this = shift;
my $string = shift;
my $length = length($string);
my $target = length($replace_this);
for(my $i=0; $i<$length - $target + 1; $i++) {
if(substr($string,$i,$target) eq $replace_this) {
$string = substr($string,0,$i) . $with_this . substr($string,$i+$target);
return $string; #Comment this if you what a global replace
}
}
return $string;
}