Recursively find text in files (PowerShell) - string

I want to find all files in a particular directory that contain a certain string. Specifically, I want to find the carriage return (\r) and then manually go through the files and remove occurrences of it. I don't want PowerShell to remove them because there may be certain subdirectories that require them in my directory structure.

Your question seems to boil down to: I want to find all files in a directory that contain the carriage return. Is there any reason why these answers are not adequate?
For example:
This should give the location of the files that contain your pattern:
Get-ChildItem -recurse | Select-String -pattern "dummy" | group path | select name

You could use Select-String to find patterns in a group of files, however this will only search for the pattern within each line of text. It will not work in your case because you want to search for the line separator.
An easier way is to use Get-Content, this converts a file to an array of strings, one item per line. Therefore any file that has a return and a line feed will produce an array with more than one item. Try something like this:
Get-ChildItem -recurse | ? {(Get-Content $_.FullName).count -gt 1}
If your files are quite large and you want to speed it up then add a -TotalCount like this:
Get-ChildItem -recurse | ? {(Get-Content $_.FullName -TotalCount 2).count -gt 1}
This will only find where the return and line feed are together, if you want instances where they could appear on their own then you will need to force Get-Content to not read the file as an array of strings but as one big string instead. Something like this:
Get-ChildItem -recurse | ? {[regex]::Matches((Get-Content $_FullName -Raw), '[\r\n]+').Count -gt 0}

Related

Replace whole text in a text file using command prompt?

Is there a way to replace whole text from a text file using command prompt? As far as I have come across is about replacing part of a text through find and replace. Is there a way to replace the complete texts from text file?
powershell -Command "(gc Pro.txt) -replace 'One', 'Two' | Out-File -encoding ASCII Pro.txt"
Found it, the way to replace whole text is:
#echo myText > Pro.txt

PowerShell - Remove certain string from multiple filenames

I have multiple .mp3 files in the catalogue and want to remove artist's name from their filenames.
All the files' names contain string
"Adhesive Wombat - "
followed by the song's title.
I want to remove (not replace) every occurence of that specific string in every filename in current folder.
Not to mention, I've searched for answer on this site and failed to find an elegant and satisfying solution.
This is my first encounter with PowerShell.
As you know what you have is really close.
Dir | ren -NewName { $_.Name -replace "Adhesive Wombat - ", "" }
You added a stipulation that "Adhesive Wombat" may or may not contain a space. -replace uses regular expressions so lets harness that and make that space optional using a ?. I am also going to show you the full cmdlet name as supposed to aliases so you are aware of what is happening behind the scenes. It's hard to see but I tried to highlight the ? in bold for it to "pop".
Get-ChildItem | Rename-Item -NewName {$_.Name -replace "Adhesive ?Wombat - ", "" }
So that will match both
"other text Adhesive Wombat - other text "
"other text AdhesiveWombat - other text "
Also, depending on how much white space there is you could use \s+ where you have space which will match all consecutive white space.
From the above answers, the quick working example for simply copy&paste, that worked on win 10 Powershell:
change directory to your target directory
define files with e.g. *.txt or set all files with *.*
insert your Strings for replacement
cd C:\....
Get-ChildItem *.* | Rename-Item -NewName {$_.Name -replace "StringtoReplace", "newString"}

Searching for specific string in a file

I need to find this pattern, "LogEntry=", across multiple lines in the following file:
C:\test.conf
And change the line to read: "LogEntry=&MAC=" instead.
The script works fine so far to do that, but if someone runs the script twice it will re-add the same pattern, doubling it up.
I need to find a way to put a check in place to know if the file already has that pattern in it. Could someone please give me a hand with this one ?
Use negative lookahead in your regex e.g.:
'LogEntry=(?!&MAC=)'
That regex will not match the already modified line. Read more about look ahead/behind zero length assertions.
BTW if you have the PowerShell Community Extensions, you can do this edit operatio with a single command:
Edit-File C:\test.conf -Pattern 'LogEntry=(?!&MAC=)' -Replace 'LogEntry=&MAC='
And if you can't use PSCX's Edit-File, here is roughly the equivalent:
$content = Get-Content C:\test.temp
$content | Foreach {$_ -replace 'LogEntry=(?!&MAC=)','LogEntry=&MAC='} | Out-File -Encoding ASCII
I don't know what the file encoding is for your file. You need to know that and use the appropriate encoding on the Out-File command. If you don't specify the encoding, it defaults to Unicode.

Scripting-Search Multiple Strings

I have a script (./lookup) that will search a file ($c). The file will contain a list of cities. What I would like to do be able to search the file for what the user enters as an argument (./lookup Miami). For example; I can make the script return what I want if it is a single word city (Miami), but I can't figure out a way to make it work for 2 or more words (Los Angeles). I can get the single strings to return what I want with the following.
grep $1 $c
I was thinking about a loop, but I am not sure on how to do that as I am new to scripting and Linux. Thanks for any help.
Whenever arguments could possibly contain spaces, proper quoting is essential in Bash:
grep "$1" "$c"
The user will need to say ./lookup "Los Angeles". If you don't like that, you can try:
grep "$*" "$c"
Then all arguments to the script will be passed together as one string to grep.

Search directory for files with specific string and print location

I need to create a perl script that will search through a given directory and find all txt files that contain a specific string. I want the perl script to then print the location of those files. So far I have accomplished that task but I want to add a few more features to the script.
This is what i have so far:
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
my $dir ='C:\path\to\dir';
my $keyword = "apple";
find(\&txtsearch, $dir);
sub txtsearch {
if(-f $_ && $_ =~ /\.txt$/) {
open my $file, "<", $_ or do {
warn qq(Unable to open "$File::Find::name": $!); #checks permissions
return;
};
while(<$file>) {
if (/\Q$keyword\E/) {
print "$File::Find::name\n"; #prints location of file
return; #stops searching once found
}
}
}
}
Now I want to add a few things:
Firstly, I would like to include a way to include capitalization in the search. For example, if I want to find all the instances of the word "apple" I don't want it to overlook any uses of "Apple" or "APPLE".
I would also like to be apple to input the keyword in the command line rather then the actual script itself.
Also, would it be possible to have the script create a file in the specified directory named "output.txt" and have the output of the script import into that? I know one the command line you will have to have something like > output.txt but I am not completely sure how to implement that in the script.
Lastly, it would be nice if I could include a printout of how many occurrences of the string are in the file. For example, if the word "apple" appears 5 times in a text file, I would like to see an output of the location of the file and also, something like "apple appears 5 times in FILE.txt"
Thank you so much for the help!
Firstly, I would like to include a way to include capitalization in the search. For example, if I want to find all the instances of the word "apple" I don't want it to overlook any uses of "Apple" or "APPLE".
Add i modifier to your regex
Reference: perldoc perlre
I would also like to be apple to input the keyword in the command line rather then the actual script itself.
Use GetOpt::Long module for command line parameter processing.
Reference: GetOpt::Long
Also, would it be possible to have the script create a file in the specified directory named "output.txt" and have the output of the script import into that? I know one the command line you will have to have something like > output.txt but I am not completely sure how to implement that in the script.
Open a file for writing using open(my $output_filehandle, ">", "output.txt") or die "Can not open file for writing: output.txt. $!"
Then replace print <STUFF> with print $output_filehandle <STUFF> .
Reference: perldoc open and Tutorial on opening things in Perl on Perldoc
Lastly, it would be nice if I could include a printout of how many occurrences of the string are in the file. For example, if the word "apple" appears 5 times in a text file, I would like to see an output of the location of the file and also, something like "apple appears 5 times in FILE.txt"
Keep a counter variable instead of returning after first hit. Then print filename and counter after file-lines loop ends.
Reference: Basic understanding of programming and loops, not really related to Perl at all.

Resources