Skip to main content

Find file and rename on one command in bash [Resolved]

how can I find a file in rhel7 server and rename it? Can this be done in one command? Thx


Question Credit: Logan0421
Question Reference
Asked July 20, 2019
Tags: bash
Posted Under: Unix Linux
8 views
2 Answers

If you want to rename file.conf to file2.conf, use find with the -exec option:

find . -name "*.conf" -type f -exec sh -c 'mv "$1" "${1%.conf}2.conf"' sh {} \;

Each filename {} is passed as parameter $1 to a new shell process started with the -exec option where the mv command is executed.

  • ${1%.conf} is a shell parameter expansion and removes suffix .conf from the filename
  • 2.conf adds the new suffix to the filename

If you want to test your command before executing it, add an echo to it like:

find . -name "*.conf" -type f -exec sh -c 'echo mv "$1" "${1%.conf}2.conf"' sh {} \;

credit: Freddy
Answered July 20, 2019
Your Answer
D:\Adnan\Candoerz\CandoProject\vQA