Link to home
Start Free TrialLog in
Avatar of xbox360dp
xbox360dp

asked on

Rename file based on contents in the file?

Gurus,

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

Example:

Filename: -.log
Contents:
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.
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

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

ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start 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.