1

In bash, I want to search a directory which contains a file that I'm expecting:

find . -name "myfile-*.war" 

assign the name of this file to a variable, and then rename the file to newfile.war.

10
  • 1
    Is the file in the directory directly or in some sub-(sub-?)directory of it? Commented Jun 26, 2015 at 20:14
  • Is the assignment to a variable essential, or is it superfluous if the renaming gets done by other means? Are you sure that there will be only one file which matches your search parameter? Commented Jun 26, 2015 at 20:17
  • 1
    If there is only one file, and no subdirectories, why do you need find? Commented Jun 26, 2015 at 20:19
  • the assignment to a variable is not essential, but a nice to have. I am not 100% sure there is only a single file that matches Commented Jun 26, 2015 at 20:21
  • 1
    And if there are multiple matches in one subdirectory, all but one of them should be deleted, because only one of them can be called newfile.war? Commented Jun 26, 2015 at 20:24

2 Answers 2

3

If you are sure the find command will return exactly 1 file you can use this:

name=$(find . -name "myfile-*.war" )
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to assign the file to a variable, just rename it with the -execdir option to find:

find . -name 'myfile-*.var' -execdir mv {} newfile.war \;

3 Comments

Perhaps mention that this will effectively remove files if there are multiple matches in the same directory. They will all be renamed on top of each other, successively replacing the previously renamed file.
Wouldn't this move the file to find's working directory?
Good catch. I changed to -execdir so it runs the command inside the directory of the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.