brux
brux

Reputation: 3230

linux command line rename all files with supplied argument

trying to rename all files in a directory to $arg[1] + number of file.

for example these files:

gfdgfdh.jpg  
fgdsyugfs.jpg  
gfyudsfuds.jpg  

will become the following when i do sh myscript.sh dog at the command line:

dog0.jpg
dog1.jpg
dog2.jpg

Here is the code I have so far, the regex works because if it try the rename command on one file from the command line it works.

#! /bin/sh
COUNTER=0
PREFIX=$1
for i in *.jpg
do
        rename 's/.*[^.jpg]/${PREFIX}${COUNTER}/' $i
        COUNTER=COUNTER+1
done

The error I get is

Global symbol "$PREFIX" requires explicit package name at (eval 1) line 1.

Upvotes: 1

Views: 2835

Answers (3)

Roman Rhrn Nesterov
Roman Rhrn Nesterov

Reputation: 3673

with "rename" command

rename 's/.*/dog$N.jpg/' *.jpg

Upvotes: 0

Sorin
Sorin

Reputation: 5415

rename accepts a perl program/expression and in your case the $PREFIX is interpreted as a variable.

rename is a tool to bulk rename files, you are using it to rename only a file. A better approach would be:

PREFIX=dog; 
rename  "s#[^/]*.jpg#'$PREFIX' . \$main::C++ . '.jpg'#e" tmp/*.jpg

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363818

The error is caused by the fact that you put $PREFIX inside '', which doesn't expand it, but passes it to the Perl program rename, which in turn seems to evaluate the pattern as Perl code.

Another mistake in your script is COUNTER=COUNTER+1. The shell just doesn't work that way. Try this instead (untested):

#!/bin/sh
prefix=$1

count=0
for f in *.jpg; do
    mv "$f" "$prefix$count".jpg
    count=`expr $count + 1`
done

Upvotes: 4

Related Questions