1

On my Qnap I'm trying to replace "xyz" in filenames to "abc" in files in multiple directories. Being a unix/linux newbie, i tried the following command:

for f in *xyz*; do mv -i "$f" "${f//xyz/abc}"; done

This works perfect for the files in a directory, but does not work for files in the sub-directories. How can I change the above to also make it work for files in the subdirectories ?

8
  • What shell do you use? In bash you could use globstar. Commented Feb 3, 2020 at 21:09
  • I use MacOs terminal to SSH into my Qnap Commented Feb 3, 2020 at 21:26
  • OK, I asked what shell do you use on your Qnap? If you're not sure post output of echo $SHELL or press Control-x Control-v and check if something like GNU bash, version 4.3.46(1)-release (x86_64-slackware-linux-gnu) shows up on the screen. Commented Feb 3, 2020 at 21:28
  • exciting echo $SHELL gives me: /bin/sh Commented Feb 3, 2020 at 21:30
  • ctrl-x ctrl v gives me: GNU bash, version 3.2.57(1)-release (x86_64-QNAP-linux-gnu) Commented Feb 3, 2020 at 21:36

1 Answer 1

0

As discussed in the comments OP uses bash shell on their QNAP device but since it's Bash 3 globstar cannot be used because in was added in Bash 4.0. In that case find is one of the possible solutions.

Example:

First, create an example directory structure and create xyz files:

$ mkdir -p 1/2/3
$ touch  a_xyz_a 1/2/b_xyz_b 1/2/3/c_xyz_c

Now run find + mv:

$ find . -name "*xyz*" -exec sh -c 'echo mv -i "$1" "${1//xyz/abc}";' sh {} \;
mv -i ./a_xyz_a ./a_abc_a
mv -i ./1/2/3/c_xyz_c ./1/2/3/c_abc_c
mv -i ./1/2/b_xyz_b ./1/2/b_abc_b

Remove echo to actually execute mv.

6
  • Thank you for all the efforts, the above line gives me: -sh: $: command not found Commented Feb 3, 2020 at 22:02
  • Do not copy the initial $, it's here to represent prompt. Commented Feb 3, 2020 at 22:02
  • euhm.. i'm so glad i put newbie in my nick :) Commented Feb 3, 2020 at 22:08
  • Yes, it's good :) Does it work for you? Commented Feb 3, 2020 at 22:08
  • Works like a charm, thank you very much Commented Feb 3, 2020 at 22:21

You must log in to answer this question.

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