Alex Rivera | Logout

Find and replace filename recursively in a directory

Asked 2012-02-22T11:07:54.567
57

I want to rename all the files in a folder which starts with 123_xxx.txt to xxx.txt.

For example, my directory has:

123_xxx.txt
123_yyy.txt
123_zzz.txt

I want to rename all files as:

xxx.txt
yyy.txt
zzz.txt

I have seen some useful bash scripts in this forum but I'm still confused how to use it for my requirement.

Let us suppose I use:

for file in `find -name '123_*.txt'` ; do mv $file {?.txt} ; done

Is this the correct way to do it?

Edit
Report

2 Answers

8

you could check 'rename' tool

for example

rename 's/^123_//' *.txt

or (gawk is needed)

find . -name '123_*.txt'|awk '{print "mv "$0" "gensub(/\/123_(.*\.txt)$/,"/\\1","g");}'|sh

test:

kent$  tree
.
|-- 123_a.txt
|-- 123_b.txt
|-- 123_c.txt
|-- 123_d.txt
|-- 123_e.txt
`-- u
    |-- 123_a.txt
    |-- 123_b.txt
    |-- 123_c.txt
    |-- 123_d.txt
    `-- 123_e.txt

1 directory, 10 files

kent$  find . -name '123_*.txt'|awk '{print "mv "$0" "gensub(/\/123_(.*\.txt)$/,"/\\1","g");}'|sh

kent$  tree
.
|-- a.txt
|-- b.txt
|-- c.txt
|-- d.txt
|-- e.txt
`-- u
    |-- a.txt
    |-- b.txt
    |-- c.txt
    |-- d.txt
    `-- e.txt

1 directory, 10 files
answered 2012-02-22T11:17:53.740
4

A slight variation on Kent's that doesn't require gawk and is a little bit more readable, (although, thats debatable..)

find . -name "123*" | awk '{a=$1; gsub(/123_/,""); printf "mv \"%s\" \"%s\"\n", a, $1}' | sh

answered 2012-02-22T11:41:12.800

Your Answer