How to better troubleshoot/debug Powershell [closed] - regex

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
EDIT
My Regex was off, though, I'm having the same issue stull
https://regex101.com/r/wUHyZm/4
I was able to paste in a huge amount of input and got 50 matches using the link above, but still can't get powershell to flag a match.
Please see the below link for my regex and sample input
https://regex101.com/r/wUHyZm/4
https://regex101.com/r/wUHyZm/2
Basically I have a folder with a bunch of sub folders.
My script parses through each subfolder looking for "results.nmap".
It then opens the file (a text file) and I am intending for it to extract data that meets certain requirements.
Get-ChildItem -LiteralPath "U:\nmap reports\Nmap Subnet Scans\August2019" -Filter *.nmap -File -Recurse | foreach {
$currentfolder = $_.Directory
$RegX = [RegEx]'(?m)^Nmap scan report for\s+(?<Device>.+)\r?\n(?:.+\r?\n){3,6}23\/tcp\s+open\s+telnet$'
$content = Get-Content -Path "$currentfolder\results.nmap" -Raw
if ($content -match $RegX) {
Write-Host 'issa match'
}
#write-host $content
#[regex]::Matches($content,$RegX).ForEach({ $_.Groups['Device'].Value })
}
I can't seem to get it to match in powershell, but it matches in the link above.
I also don't get any errors
I had a previous question regarding the regex side, and a kind user provided:
[regex]::Matches($content,$RegX').ForEach({ $_.Groups['Device'].Value })
Which doesn't yield results either, though logically I don't see why it wouldn't.
Write-Host $content
Looks exactly like it should in my provided link above.
I'm not looking for an answer, moreso I'm looking for a good way to troubleshoot this so I can better teach myself

In the ISE, you can use the debugger to step or set breakpoints, and run any arbitrary powershell command at the debug prompt, and mouse over variables to see their current value.
You can change the value of a variable and continue running. Even write a new function.

Related

unix change number's value on given line number in shell script for loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How can I change a number on a line in a file using a unix tool like awk or sed?
I want to change the line 3 in my example file to the number 1-10 using a shell script. I think I need to use regex to recognize the digit but I'm not sure how to do this, or to allow multiple digits (like 10).
Example file:
/examples/are/hard so/hard/1
Shell script so far:
for i in {1..3};
do
sed 's|/examples/are/hard so/hard/7 | /examples/are/hard so/hard/'"$i" ex_file
cat ex_file
done
Desired output:
/examples/are/hard so/hard/1
/examples/are/hard so/hard/2
/examples/are/hard so/hard/3
What you've run isn't a valid sed command. If you're trying to do a substitution, that's s/search/replace/flags.
I imagine you meant:
sed 's/here\/is the number\/to\/change 3/here\/is the number\/to\/change '"$i"'/' ex_file
Note that we temporarily break out of single quote. Inside of single quotes, variable aren't interpolated. We swap the double quotes, bring in $i, then return to single quotes to finish the command.
P.S. You also don't have to use / as your delimiter.
sed 's|here/is the number/to/change 3|here/is the number/to/change '"$i"'|' ex_file

Alternative to many substitutions in a row? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Most of my Perl scripts deal with converting ugly formats to the plain TXT content. So far, I've done this with dozens and dozens of substitutions all in a row. Is there a more elegant way to do this in Perl? For instance, a hash containing all the s/// pairs, or even an external file containing the substitutions?
I'm just wondering how other people handle this kind of formatting script, or if just having a novel's worth of s/// expressions is the normal way to go. It gets hard to manage at a certain point.
Thanks!
Sometimes the most efficient approach is to parse the old data format into a memory structure and then output the new format.
Depending on the structure, this can be done line by line. But if you have to do the whole document that works, as long as they aren't too gigantic.
As an example, this is how you'd do an image file conversion: read a GIF into a bitmap and then produce a JPEG output. You wouldn't use regular expressions, even if you could, it would be horribly inefficient.
I have a utility method I use all the time for this:
sub subst($#) {
my($x, #map) = #_;
#map % 2 == 0 or die 'subst requires an odd number of params';
while (#map) {
my $from = shift(#map);
my $to = shift(#map);
$x =~ s/$from/$to/g;
}
return $x;
}
I use a list instead of a hash for map so I can control the order. Use it like this:
my $new_x = subst($x,
pattern1 => replacement1,
pattern2 => replacement2);
Even with a single pattern, it's simpler if you aren't substituting something in place. I.e. it's cleaner than this:
my $new_x = $x;
$new_x =~ s/pattern1/replacement1/g;
Zan Lynx gives good advice, but to answer your question about hash-driven substitutions, you can use the following:
my %replacements = (
foo => 'bar',
bar => 'baz',
baz => 'foo',
# ...
);
my $pat = join '|', map quotemeta, keys %replacements;
s/($pat)/$replacements{$1}/g;
This solves two problems:
It scans the input only once, not once per pattern.
It takes away the risk of accidentally matching the replacements of earlier substitutions. In fact, the example I used couldn't be accomplished with three substitutions.
This is an awkward question because the order of the substitutions affects the result
If your changes are so extensive then I would much prefer a sequence of s/// statements to anything held in a hash, which would shuffle the substitutions into a different order each time the program was run
I would still be worried about the accuracy of “dozens and dozens” (two hundred plus?) of substitutions, but at least the result would be under control

cmd: replace inner part of a filename (using regular expression mask) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I run a small batch-file to rename some txt-file:
"C:\backup\t1-dd-dd t2-dd-dd.txt"
in the filename d - is a digit (from 0 to 9);
note: there is space in the filename between t1 and t2 marks (I need it for some reason).
now, I need to replace digits only in the 't1-dd-dd' part of the filename.
with powershell Rename-Item it can be done like this (example):
powershell -command "& { Get-ChildItem с:\backup -filter 't1-* t2-*.txt' | Rename-Item -NewName { $_.Name -replace 't1-\d\d-\d\d','t1-00-99' } }"
result would be like this:
C:\backup\t1-14-26 t2-56-48.txt (old filename)
C:\backup\t1-00-99 t2-56-48.txt (new filename)
is it possible to do same thing without powershell, just using cmd RENAME command?
You can't do it with regex, but you can do it with RENAME wildcards.
ren "c:\backup\t1-??-?? t2-??-??.txt" "???00-99*"
Within the target mask, each ? preserves one character, and the literals do a one for one character replacement, and the * preserves the remainder.
See How does the Windows RENAME command interpret wildcards? for more info.
If you are worried that the source mask is not specific enough, then you could use the following batch script to guarantee only properly named files are renamed.
pushd "c:\backup"
for /f "delims=" %%F in (
'dir /b /a-d "t1-??-?? t2-??-??.txt" ^| findstr /xirc:"t1-[0-9][0-9]-[0-9][0-9] t2-[0-9][0-9]-[0-9][0-9].txt"'
) do ren "%%F" "???00-99*"
popd
But your powershell script is probably easier :-)

Write an output file superset of 3 files with no lines repeated in it [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have three text files 1.txt, 2.txt and 3.txt, which are outputs of a perl script. There are some common lines in all the 3 files. Please help to write a perl script whose output is another text file which is superset of 1.txt and 2.txt and 3.txt and should not have lines repeated in it.
The easiest way to do this is to use a hash to keep track of lines you've seen before. For very large files, this will take too much memory, however.
use strict;
use warnings;
use autodie 'open';
open my $out, '>', 'superset.txt';
my %seen;
for my $filename ('1.txt', '2.txt', '3.txt') {
open my $in, '<', $filename;
while ( my $line = <$in> ) {
print $out $line unless $seen{$line}++;
}
}
Perl one liner for unique lines in .txt files,
perl -ne '$s{$_}++ or print' *txt > out.txt

how to replace ’ with ’ in perl [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have below piece of code in Perl
my $file2 = "devil’s-claw-extract.html";
$file2 =~ s/’/’/ig;
print "$file2";
This code is working fine(means replacing ’ with ’) when running in konsole but not working in browser.
Please help me out.
Of course it “works”, and I will believe so until you produce a self-contained example that indicates otherwise.
Your first problem is that you are reinventing the wheel, there already is a module on CPAN to do such escaping for you:
use utf8; # because this source file contains special chars
use HTML::Entities;
my $file2 = "devil’s-claw-extract.html";
print encode_entities $file2;
Output:
devil’s-claw-extract.html
or with encode_entities_numeric:
use utf8;
use HTML::Entities 'encode_entities_numeric';
my $file2 = "devil’s-claw-extract.html";
print encode_entities_numeric $file2;
Output:
devil’s-claw-extract.html
Secondly, it is worth noting that your input string contains ’, a single right quote. This has the codepoint U+2019 (not U+0092, which is in a private use area. Conveniently, it decodes to ’ in the Windows-1252-encoding, but the actual encoding should always be explicitly set).
The apostrophe ', which you likely wanted, is U+0027 or &apos;.