3

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

Saxena Shekhar
  • 219
  • 6
  • 22

3 Answers3

3

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
chaos
  • 8,162
  • 3
  • 33
  • 40
  • Will this solution work if `test.text` be not in the current directory? – Tim Biegeleisen Apr 15 '15 at 09:24
  • By "work" do you mean will it find some other file than the one you are telling it to find in the current directory? Of course not. `mv` simply examines the file name parameter; if you say `mv path/to/file.txt path/to/file.txt.bak` then it will look in `path` in the current directory and then `to` inside that. If you use an absolute file name, it will use that. – tripleee Apr 15 '15 at 10:20
  • @tripleee Yes, ur right, but how the question is written: "then I fire the command mv test.text test.text.bak", I think the op won't search a whole directory structure, only a file inside the current working dir. – chaos Apr 15 '15 at 10:55
  • 2
    @chaos Suppressing the error message is one thing; but still mv returns with a non-zero exit code if test.text doesn't exist; which might or might not be what you want to happen. – GhostCat Nov 03 '15 at 08:06
3

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.)

tripleee
  • 175,061
  • 34
  • 275
  • 318
1
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

VivekD
  • 318
  • 1
  • 11
  • This runs multiple commands, by any useful definition, and will fail on files whose names contain whitespace or other shell metacharacters. The simplest, most robust fix is probably to switch to `find -exec mv` but then that duplicates my answer. – tripleee Dec 23 '16 at 11:04