I want to search the following string in a text file: $$u$$
I tried select-string, get-content, .Contains. It seems to me it's not possible.
I used this for the search as a variable: $ToSearch = "'$'$u'$'$"
It always gives false result.
It is because most search filters are relying on regex. The $ symbol in regex needs to be escaped
Without knowing more of what you're trying to accomplish I can't give much of an example, but here is one:
'this is a $$u$$ test' -replace "\$",""
The '\' is what is escaping the character - meaning to translate it literally.
Edit: Per comment
$Val = 'this is a $$u$$ test'
$Val | Select-String "\$+\w\$+" -quiet
-Quiet switch returns t/f rather than a string value.
The $ is a reserved character in regex, which is complicating your search.
The default search pattern type for Select-String is regex, but you can also specify -Simplematch or -Wildcard, either of which will eliminate the need to escape the $. If you use -Wildcard, you'll need to include the wilcard * at either end of the match - '*$$u$$*'. For simplematch, just use the string you want to match for - '$$u$$'.
Related
I need to drop (or replace to nothing) last n characters of a string in powershell code. The variant could be with substraction string form a string (didn't find my answer).
I have something like this (string):
something/something/../lastsomething/NAME
where NAME is a variable text I can extract beforehand and manipulate ($name or $name.length). And the whole string can be counted - $string.length.
How can I substract this NAME from a string ($string)? I've searched many ways, including trim,replace,substring - but all of these mostly work with static words or regex, or with the begining of a string.
I need to get this:
something/something/../lastsomething
I've tried even such constructions:
$string.split('($NAME)')[0]
and
$string.split('[string]($NAME)')[0]
and other with get-AD* functions with join to bypass the strings, but nothing did the trick.
A simple solution is take the substring from beginning (0) to the last occurence of /.
$t = 'something/something/../lastsomething/NAME'
$t.Substring(0, $t.LastIndexOf('/'))
EDIT from your comment the real question is how to get
-replace '($_.Name)',' '
working. The single quotes don't expand variables - so use double quotes.
To force evaluation of $_.Name you have to enclose it with $()
-replace "/$($_.Name)"
With an unknown last element /Name
> $String = 'something/something/../lastsomething/NAME'
> $String.Split('/')[-1]
NAME
> $string = $string -replace "/$($String.Split('/')[-1])"
> $string
something/something/../lastsomething
A much simpler solution is :
> Split-Path $string
something\something\..\lastsomething
> Split-Path $string -Leaf
NAME
but it changes slashes to backslashes
You can replace it with '' (nothing ... empty string) and because -replace works with regular expressions you can make sure that you only get a "match" at the end of the string like this:
$var = '/NAME'
'something/Name/something/../lastsomething/NAME' -replace "$var$",''
I have a few strings like this:
var1="string one=3423423 and something which i don't care"
var2="another bigger string=413145 and something which i don't care"
var3="the longest string ever=23442 and something which i don't care"
These strings are the output of a python script (which i am not allowed to touch), and I need a way to extract the 1st part of the string, right after the number. Basically, my outputs should be:
"string one=3423423"
"another bigger string=413145"
"the longest string ever=23442"
As you can see, i can't use positions, or stuff like that, because the number and the string length are not always the same. I assume i would need to use a regex or something, but i don't really understand regexes. Can you please help with a command or something which can do this?
grep -oP '^.*?=\d+' inputfile
string one=3423423
another bigger string=413145
the longest string ever=23442
Here -o flag will enable grep to print only matching part and -p will enable perl regex in grep. Here \d+ means one or more digit. So, ^.*?=\d+ means print from start of the line till you find last digit (first match).
You could use parameter expansion, for example:
var1="string one=3423423 and something which i don't care"
name=${var1%%=*}
value=${var1#*=}
value=${value%%[^0-9]*}
echo "$name=$value"
# prints: string one=3423423
Explanation of ${var1%%=*}:
%% - remove the longest matching suffix
= - match =
* - match everything
Explanation of ${var1#*=}:
# - remove the shortest matching prefix
* - match everything
= - match =
Explanation of ${value%%[^0-9]*}:
%% - remove the longest matching suffix
[^0-9] - match any non-digit
* - match everything
To perform the same thing on more than one values easily,
you could wrap this logic into a function:
extract_and_print() {
local input=$1
local name=${input%%=*}
local value=${input#*=}
value=${value%%[^0-9]*}
echo "$name=$value"
}
extract_and_print "$var1"
extract_and_print "$var2"
extract_and_print "$var3"
$ shopt -s extglob
$ echo "${var1%%+([^0-9])}"
string one=3423423
$ echo "${var2%%+([^0-9])}"
another bigger string=413145
$ echo "${var3%%+([^0-9])}"
the longest string ever=23442
+([^0-9]) is an extended pattern that matches one or more non-digits.
${var%%+([^0-9])} with %%pattern will remove the longest match of that pattern from the end of the variable value.
Refs: patterns, parameter substitution
I've got the command below:
> "D:\abc\abcName".TrimStart("D:\abc")
Name
In fact I wish this to trim exactly "D:\abc" and return only "abcName" but seems that the 2nd "abc" is trimmed off as well.
Why does this happen and how can I fix it?
I'm using PS 4.0.
The argument to TrimStart() is treated as an array of chars, not a literal string. All consecutive characters at the start of the string that match any of the characters inside the argument "D:\abc" is removed.
You could use the -replace operator instead, which takes a regex pattern as its right-hand argument:
PS C:\> "D:\abc\abcName" -replace "^D:\\abc\\"
abcName
If you are unsure which characters to escape (such as \), let the [regex] class do it for you:
PS C:\> "D:\abc\abcName" -replace "^$([regex]::Escape("D:\abc\"))"
abcName
Mathias R. Jessen points it out.
Looks like you want to get the filename from a path. Instead of using TrimStart consider use the static GetFileNameWithoutExtension method:
[system.io.path]::GetFileNameWithoutExtension("D:\abc\abcName.bat")
Result:
abcName
Or if you want the complete filename with extension:
[system.io.path]::GetFileName("D:\abc\abcName.bat")
Result:
abcName.bat
I have something like:
$string = '/mfsi_rpt/files/mfsi/reports/bval/bval_parlcont_pck_m_20130430.pdf';
I would like to extract the parlcont from the string (the word between the 2nd and 3rd underscore).
What is the best way to achieve this using Perl?
You can match this with a regular expression, by combining greedy and non-greedy matches, and using capturing parenthesis to extract the part you're interested in:
if( $string =~ m:.+/.*?_(.+?)_:) {
print "$1\n";
}
The ".+/" is a greedy match, which will gobble up everything up to the last / to get past the directory components.
Then the ".*?_" is non-greedy, so it will take everything up to the first _
Then "(.+?)_" is another non-greedy to match and capture everything up to the next _
It would be nice if you first take out the filename from the file path using File::Basename then you can use split to take out the desired name.
use strict;
use File::Basename;
my $string = "/mfsi_rpt/files/mfsi/reports/bval/bval_parlcont_pck_m_20130430.pdf";
my $data = ( split( /_/, basename($string) ))[1];
Output:
parlcont
Is there an easy way, using a subroutine maybe, to print a string in Perl without escaping every special character?
This is what I want to do:
print DELIMITER <I don't care what is here> DELIMITER
So obviously it will great if I can put a string as a delimiter instead of special characters.
perldoc perlop, under "Quote and Quote-like Operators", contains everything you need.
While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching
capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of
them. In the following table, a "{}" represents any pair of delimiters you choose.
Customary Generic Meaning Interpolates
'' q{} Literal no
"" qq{} Literal yes
`` qx{} Command yes*
qw{} Word list no
// m{} Pattern match yes*
qr{} Pattern yes*
s{}{} Substitution yes*
tr{}{} Transliteration no (but see below)
<<EOF here-doc yes*
* unless the delimiter is ''.
$str = q(this is a "string");
print $str;
if you mean quotes and apostrophes with 'special characters'
You can use the __DATA__ directive which will treat all of the following lines as a file that can be accessed from the DATA handle:
while (<DATA>) {
print # or do something else with the lines
}
__DATA__
#!/usr/bin/perl -w
use Some::Module;
....
or you can use a heredoc:
my $string = <<'END'; #single quotes prevent any interpolation
#!/usr/bin/perl -b
use Some::Module;
....
END
The printing is not doing special things to the escapes, double quoted strings are doing it. You may want to try single quoted strings:
print 'this is \n', "\n";
In a single quoted string the only characters that must be escaped are single quotes and a backslash that occurs immediately before the end of the string (i.e. 'foo\\').
It is important to note that interpolation does not work with single quoted strings, so
print 'foo is $foo', "\n";
Will not print the contents of $foo.
You can pretty much use any character you want with q or qq. For example:
#!/usr/bin/perl
use utf8;
use strict; use warnings;
print q∞This is a test∞;
print qq☼\nThis is another test\n☼;
print q»But, what is the point?»;
print qq\nYou are just making life hard on yourself!\n;
print qq¿That last one is tricky\n¿;
You cannot use qq DELIMITER foo DELIMITER. However, you could use heredocs for a similar effect:
print <<DELIMITER
...
DELIMETER
;
or
print <<'DELIMETER'
...
DELIMETER
;
but your source code would be really ugly.
If you want to print a string literally and you have Perl 5.10 or later then
say 'This is a string with "quotes"' ;
will print the string with a newline.. The importaning thing is to use single quotes ' ' rather than double ones " "