We help IT Professionals succeed at work.

Script for finding and replacing text in a file name

Medium Priority
68 Views
Last Modified: 2020-01-31
Hello,

I am looking for a way to scrip a check of a file where it will read the first line in the file looking for a word like "Apple" in the text file, once it finds it I would like to change the name of the of the file using the word found in the middle of the file name.

For example, the file name 123_xxxxxxxxx.txt contains text in the first line that has the word Apple and if that word exists I need to change the name of that file to this 123_Apple_xxxxxxxxx.txt.  Now if the word I am looking for is not there then no changes need to be made to the file. Also, I would like to ignore any other files that do not start with 123, say 134 for instance.

I would prefer to run this on Windows as much as possible and I would be running it on Windows 7 but might be moving to Windows 10 in the future.

Nathan
Comment
Watch Question

Senior Systems Admin
CERTIFIED EXPERT
Top Expert 2010
Commented:
$allfiles = dir 123*.txt 
foreach ($file in $allfiles){
   $content = get-content $file
   $variable = ($file.name.Split("_"))[1]
   if ($content -like "*Apple*"){
      $newname = "123_Apple_" + $variable
      rename-item -path (dir $file).versioninfo.filename -newname $newname
   }
}

Should cover it for you. 

Nathan SchuetzNetwork Administrator

Author

Commented:

Adam,


Thanks for the responce. Yes, this does solve my problem. It took me a few minutes to figure out that this was a Powershell scrip. Thanks again.