Lego
Lego

Reputation: 191

Rename files in directory using a script

Our SVN users are uploading files with a certain tag name like,

filename_INT filename2_INT filename3_INT

I need my script to rename these files by removing the _INT to its original filename like

filename filename2 filename3

What is the best method to do this in bash?

I tried using sed but it fails on the script but not on the command line,

[root@hostname tags]# echo filename_INT | sed 's/_INT[a-z.]*//g'

filename.php

Upvotes: 1

Views: 126

Answers (4)

cforbish
cforbish

Reputation: 8829

The rename command should be your best bet. My man page tells me (I verified) that this works:

rename _INT "" *_INT

Upvotes: 0

janos
janos

Reputation: 124824

This one-liner should take care of all the *_INT files in the current directory:

for file in *_INT; do mv "$file" "${file%_INT}"; done

If you want to do it recursively for all files and subdirectories, you can do like this:

find path -name '*_INT' | sed -e 's/\(.*\)_INT$/mv "&" "\1"/'

The output of this is a bunch of mv commands printed but NOT executed. If it looks good and you want to execute it, just pipe it to sh like this:

find path -name '*_INT' | sed -e 's/\(.*\)_INT$/mv "&" "\1"/' | sh

Upvotes: 6

David W.
David W.

Reputation: 107090

Does this need to be done in your Subversion repository, or just locally?

If just locally, you can use find to find all of your files:

find . -name "*_INT"

Do the files have white spaces in their names? If not, the following should work:

find . -name "*_INT" | while read file
do
    mv $file ${file%_INT}
done

The ${file%_INT} uses a bash/kornshell mechanism called Pattern Matching Operators. These can quickly filter off prefixes and suffixes from file names. For example, if:

$ file=foo.txt_INT
$ echo $file         #Prints "foo.txt_INT"
$ echo ${file%_INT}  #Prints "foo.txt"
$ echo ${file#foo}   #Prints ".txt_INT"

Now that you have the file's old name and new name, you can simply use the mv command. Of course, there could be a file already existing with that name. Is that okay for that to get overwritten. If not, you'll have to figure out how to handle it:

find . -name "*_INT" | while read file
do
    if [ ! -e $file ]
    then
        mv $file ${file%_INT}
    else
        echo "File ${file%_INT} already exists"
    fi
done

Upvotes: 1

James
James

Reputation: 4737

If you have access to the rename command:

rename 's/_INT//' *_INT

Upvotes: 0

Related Questions