-1

I need the program to find filename with certain string, then rename it. That part is working. But i need to add some user input that will ask the user before every renaming if he wants to rename the file or not. Then after it finds all the files it should write filenames that were renamed. The command I have only renames all files that matches the string.

find . -type f -exec rename's/(.*)\/(.*)string1(.*)/$1\/string2$2string3$3/' {} + ;;
2
  • the program should ask before any renaming, if the file to be renamed?
    – A.B.
    Dec 29, 2015 at 21:30
  • Yes, and every renaming after that. Right now it just renames everything. So the command is not optimal for that purpose i think.
    – Daniel
    Dec 29, 2015 at 21:38

1 Answer 1

4

You could use the find command's -ok action in place of the -exec

From man find

-ok command ;
          Like  -exec but ask the user first.  If the user agrees, run the
          command.  Otherwise just return false.  If the command  is  run,
          its standard input is redirected from /dev/null.

For example, given

$ touch file{A..F}
$ ls
fileA  fileB  fileC  fileD  fileE  fileF

then

$ find . -name 'file*' -ok rename -v -- 's/file/newfile/' {} \; >rename.log
< rename ... ./fileB > ? y
< rename ... ./fileC > ? n
< rename ... ./fileF > ? n
< rename ... ./fileD > ? y
< rename ... ./fileE > ? n
< rename ... ./fileA > ? y

and

$ cat rename.log 
./fileB renamed as ./newfileB
./fileD renamed as ./newfileD
./fileA renamed as ./newfileA

Note that you can't use the + multi-argument form (since each rename command needs to be processed separately).

5
  • This works great but I have no idea how to put it in a script that would rename it recursively and then print renamed files in the command line.
    – Daniel
    Dec 29, 2015 at 22:59
  • @Daniel sorry I don't understand: find is inherently recursive; if you want the list of renamed files on the command line instead of in a log file, just remove the >rename.log Dec 29, 2015 at 23:06
  • Is there a way to put the command "find . -name 'file*' -ok rename -v -- 's/file/newfile/' {} \;" into bash script?
    – Daniel
    Dec 29, 2015 at 23:37
  • @Daniel yes you can put any command in a script - however I'm not clear from your original question exactly what you are trying to do. If you have specific questions then please post them: remember that single quotes prevent variable expansion - perhaps that's the issue? Dec 29, 2015 at 23:45
  • It was just my dumbness I guess, I'm a begginer. Sorry that I was not clear enough. Finally I've got it working exactly as I wanted. Many thanks to you for making the issue clear.
    – Daniel
    Dec 30, 2015 at 0:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .