Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

If I have a directory1 which has a "file.txt" and subdirectories: "week", "today", "last month". In "week" and "last month" is also "file.txt".

directory1/
    file.txt
    week/
        file.txt
    today/
    last month/
        file.txt

How could I, using only one line command in terminal with the command mv or rename.ul, rename every "file.txt" in "directory1" into "new_file.txt" ?

share|improve this question
1  
You probably want mv, not rm, don't you? –  Alex R. Jan 16 at 17:07

4 Answers 4

Yet another one to avoid absolute path trickery:

find directory1 -name file.txt -execdir mv {}  new_file.txt \;

execdir will run the specified command from the subdirectory containing the matched file. This even eliminates the need for quoting the filename, which we know to not contain any spaces.

share|improve this answer
find directory1/ -type f  -name file.txt | while read f; do d=$(dirname $f); mv "$d"/file.txt "$d"/new_file.txt; done
share|improve this answer
    
You forgot to add quotes around $f - $(dirname "$f"). You also forgot to remove the echo. :) –  Bruno Nova Jan 16 at 17:34
    
damn you for getting there first :-) –  david_adler Jan 16 at 17:43

Still another way:

find directory1 -name file.txt -print0 | xargs -0 rename 's/file\.txt/new_file\.txt/'
share|improve this answer

Another solution:

find directory1 -name file.txt -exec bash -c 'mv "{}" "$(dirname "{}")/new_file.txt"' \;
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.