Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Renaming all files in a directory -- perl -n -p and empty files oneliner

by Discipulus (Abbot)
on Feb 02, 2021 at 11:35 UTC ( #11127809=note: print w/replies, xml ) Need Help??


in reply to Renaming all files in a directory

hello Aldebaran,

you can avoid the oneliner BEGIN block using the Maori-farewell like in perl -M'5; $counter=0' -nle ...

But you can avoid the counter at all:

>perl -nlE "say sprintf qq(caption%03s.txt),$count++" one.txt two.txt + three.txt caption000.txt caption001.txt caption002.txt

PS you get the filename currently processed in $ARGV so you can play with it:

>perl -nlE "say sprintf q(caption%03s.txt),$1 if $ARGV =~ /.*([\d]+).* +/" one01.txt one02.txt caption001.txt caption002.txt

PPS note that perl -n and perl -p both skip empty files!

ls -l -rw-rw-r-- 1 io io 0 feb 2 13:28 one.txt -rw-rw-r-- 1 io io 0 feb 2 13:28 three.txt -rw-rw-r-- 1 io io 20 feb 2 13:37 two.txt perl -nlE 'say "processed $ARGV" if eof' *.txt processed two.txt

PPPS after choroba's nice below response I cant resist to update the title and to try it:

perl -MTie::Scalar -M"5;{package SN; use parent -norequire => 'Tie::S +tdScalar';sub FETCH {print qq(Opening ${$_[0]}); ${$_[0]}}}; tie $ARG +V, SN" -nlE "say qq(\tprocessed $ARGV) if eof" 001.txt 002.txt 003.txt Opening 001.txt Opening 002.txt Opening 002.txt processed 002.txt Opening 003.txt

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: Renaming all files in a directory
by choroba (Cardinal) on Feb 02, 2021 at 13:44 UTC
    > note that perl -n and perl -p both skip empty files!

    They don't, but that part of code is not exposed to us to insert our own code into. Or is it?

    #!/usr/bin/perl -n use warnings; use strict; { package File::ShowName; use Tie::Scalar; use parent -norequire => 'Tie::StdScalar'; sub FETCH { print STDERR "Opening ${ $_[0] }.\n"; ${ $_[0] } } } BEGIN { tie $ARGV, 'File::ShowName' } print;

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11127809]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2022-12-09 23:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?