Saxena Shekhar
Saxena Shekhar

Reputation: 219

Rename file in Linux if file exist in a single command

There is need that I want to rename file in Linux if file exist in a single command.

Suppose I want to search test.text file and I want to replace it with test.text.bak then I fire the following command

find / -name test.text if it exist then I fire the command mv test.text test.text.bak

In this scenario I am executing two commands but I want this should be happen in single command.

Thanks

Upvotes: 3

Views: 8895

Answers (3)

tripleee
tripleee

Reputation: 189628

If you want to find test.txt somewhere in a subdirectory of dir and move it, try

find dir -name test.txt -exec mv {} {}.bak \;

This will move all files matching the conditions. If you want to traverse from the current directory, use . as the directory instead of dir.

Technically, this will spawn a separate command in a separate process for each file matched by find, but it's "one command" in the sense that you are using find as the only command you are actually starting yourself. (Think of find as a crude programming language if you will.)

Upvotes: 3

VivekD
VivekD

Reputation: 328

for FILE in `find . -name test.test 2>/dev/null`; do mv $FILE $FILE.bak; done

This will search all the files named "test.test" in current as well as in child direcroties and then rename each file to .bak

Upvotes: 1

chaos
chaos

Reputation: 9302

Just:

mv test.text test.test.bak 

If the file doesn't exist nothing will be renamed. To supress the error message, when no file exits, use that syntax:

mv test.text test.test.bak 2>/dev/null

Upvotes: 3

Related Questions