2

I am trying to write a perl script to add the prefix name on the file (~100 files), but i am failed to get it done.

Example case that what I means:

abc.jpg change to NYear_abc.jpg     
def.jpg change to NYear_def.jpg    
ghi.jpg change to NYear_ghi.jpg

This is what I try to search around and write it:

#!/usr/bin/perl 
for (filename in "*".jpg;)
do {rename "$filename" "prefix_$filename";}

It shows me missing operator, anyone can help?

3 Answers 3

3

I don't know about perl syntax and perl scripting but I can help you to rename all .jpg files with its rename command as following:

First you have to switch the directory that you have all .jpg there. for example if files are stored in /home/star1017/jpg-file, I type like this:

cd /home/star1017/jpg-file

then run

rename -n 's/(.*)\.jpg$/prefix_$1.jpg/' *.jpg

Match everything (.*) which is ends$ with .jpg then add a prefix_ and print matched group$1(this means print the matched group by using its back-reference) and then print the extension. Command runs for all *.jpg files.

Test:

file01.jpg renamed as prefix_file01.jpg
file02.jpg renamed as prefix_file02.jpg
file03.jpg renamed as prefix_file03.jpg
file04.jpg renamed as prefix_file04.jpg
file05.jpg renamed as prefix_file05.jpg

Or if you don't want to switch to that directory, run this:

rename -n 's/(.*)\/(.*)\.jpg$/$1\/prefix_$2.jpg/' /home/star1017/jpg-file/*.jpg

at the end, if you ensure the test, remove -n option to real rename on actual files.

4
  • sorry, are you means i just type your command directly at my xterm? or edit it at my perl script there?
    – star1017
    Dec 11, 2014 at 9:35
  • @star1017 Yes just type the command in xterm terminal and hit enter. Note that you have to change /path/to/your/*.jpg to your directory which all .jpg files are there. Dec 11, 2014 at 9:39
  • i still no manage to change it :( do you mind snapshot and show me yours history or step how to make it? thanks a lot.
    – star1017
    Dec 11, 2014 at 9:58
  • @star1017 updated answer. check please. Dec 11, 2014 at 11:22
0

You wanted a perl script, here is your Perl script ;)

#!/usr/bin/perl
use strict;
use warnings;

foreach $_ (@ARGV) {
   rename($_, "NYear_$_");
}

Assuming, the name of the script is foo, start with

./foo *.jpg

Example

% ls *.jpg
abc.jpg  def.jpg  ghi.jpg

% ./foo *.jpg

% ls *.jpg   
NYear_abc.jpg  NYear_def.jpg  NYear_ghi.jpg
0

then of course, there's the idiomatic perl one-liner:

$ ls *jpg
abc.jpg  def.jpg  ghi.jpg
$ perl -e 'rename($_, "NYear_$_") foreach @ARGV' *jpg
$ ls *.jpg   
NYear_abc.jpg  NYear_def.jpg  NYear_ghi.jpg

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .