Rename file based on contents in the file?


I have a request to rename a file based on the contents inside that file.


Filename: -.log
Date of report: 2015-08-05 19:50:31 -0400
Configuration: Attribute Definition
Job ID: 9988
Transfer file: msc_attributedef_20150805164651.csv
Line count: 2
Lines ok: -
Lines not ok: -

I need a script that will rename the -.log file to msc_attributedef_20150805164651.log. Which is the Transfer file name inside that file.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

This should do it...
use strict;
use warnings;
my $file = shift or die "Usage: $0 filename_to_rename\n";
open IN, $file or die "could not open $file: $!";
my @lines = map { chomp; s{^Transfer\s+file:\s*}{}; $_ } grep m{^Transfer\s+file:}, <IN>;
close IN;
if (@lines < 1) {
    die "could not find a Transfer file line in $file";
} elsif (@lines > 1) {
    die "found multiple Transfer file lines in $file:\n" . join("\n", @lines);
$lines[0] =~ s{\.\w+$}{.log};
rename $file, $lines[0] or die "could not rename $file to $lines[0]: $!";

Open in new window

perl -ne '($n)=/Transfer file:\s*(\w+)/ and rename $ARGV,$ARGV=~s/[^.]*/$n/r' -- -.log

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Here was what I was coming up with while the others were posting...

 perl -ne 'm/^Transfer file: (.+)\./ and close(ARGV) and rename($ARGV, "$1.log")' -.log xxx.log xxy.log 

Open in new window

I figured you might want to perform this change for more than one file.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.