Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-liner Perl command to rename files

Tags:

perl

So far this one-liner is stripping off one line and renaming the file, but I need help to alter it so that it strips that line I am looking for Data for and remove the old file extension .csv instead of adding to it. (.csv.out). I am not sure if this can be done with one-liner.

Instead it's adding on the the extension filename.csv.out

Example

 test_20110824.csv.out

One-liner:

find -type f -name '*.csv' -exec perl -i.out -wlne '/^Data for/ or print' {} \;

I want to replace the extension:

test_20110824.out
like image 843
jdamae Avatar asked Aug 25 '11 20:08

jdamae


People also ask

How do I rename a file in Perl?

Perl | rename() Function rename() function in Perl renames the old name of a file to a new name as given by the user. die ( "Error in renaming" );

Which command is used to rename files?

Use the mv command to move files and directories from one directory to another or to rename a file or directory.

How do I rename a text file in Terminal?

To rename a file in the terminal, move the file with mv from itself to itself with a new name.


2 Answers

perl -MFile::Copy -we 'for (glob "*.csv") { my ($name) = /^(.+).csv/i; move($_, $name . ".out"); }'

To remove the header matching Data for:

perl  -MFile::Copy -MTie::File -wE 'for (glob '*x.csv') { tie my @file,
"Tie::File", $_ or die $!; shift @file if $file[0] =~ /^Data for/; 
untie @file; my ($name) = /^(.*).csv/i; move($_, $name . ".out"); }'

But then it's really not a one-liner anymore...

use strict;
use warnings;
use Tie::File;
use File::Copy;
use autodie;

for (@ARGV) {
    tie my @file, "Tie::File", $_;
    shift @file if $file[0] =~ /^Data for/;
    untie @file; 
    my ($name) = /^(.*).csv/i; 
    move($_, $name . ".out");
}

And use with:

$ script.pl *.csv
like image 58
TLP Avatar answered Sep 21 '22 16:09

TLP


A simple Bash shell script will suffice

(shopt -s failglob; for i in *.csv.out; do echo mv $i ${i%csv.out}out; done)

The shopt -s failglob is needed to ensure that if there are no matches the command will fail instead of trying to rename *.csv.out to *.out. The construct ${i%csv.out}out removes a trailing csv.out and replaces it with just out.

As I have coded it here, this will just echo the commands it would execute. When you're satisfied it does what you want, remove the word echo.

like image 27
Jim Garrison Avatar answered Sep 23 '22 16:09

Jim Garrison