سؤال

I am trying to rename all files which contains 'Name' with dynamic name.

So this file 'NameSomething' should look like this 'SearchSomething'. But script below just removes 'Name' from file name.

name='search'
Name='Search'

find ../../$name-module -name 'Name*' -type f -exec bash -c 'mv "$1" "${1/Name/$Name}"' -- {} \;
هل كانت مفيدة؟

المحلول 2

\You can escape quotes, no need for an export:

find ../../$name-module -name 'Name*' -type f -exec bash -c "mv \"\$1\" \"\${1/Name/$Name}\"" -- {} \;

نصائح أخرى

You have to export Name, because otherwise the command find will not inherit the variable $Name into its environment. So:

name='search'
export Name='Search'

find ../../$name-module -name 'Name*' -type f -exec bash -c 'mv "$1" "${1/Name/$Name}"' -- {} \;

You might use find to find a list of the files you want to rename and pipe that to another program to do the renaming.

For example, you could do:

find ../../$name-module -print0 -name 'Name*' -type f | \
xargs -0 rename "s/Name/$Name/" 
  • No need for exporting (ugly + might affect other commands)
  • Rename might get run only once (if all the found files fit on one command line) (with -exec, you're running two programs -- bash and mv -- per each file. That might be inefficient.

(You could get further performance increase with this approach by using Gnu parallel instead of xargs, if you're on a multicore computer)

You could use the Perl-based rename command:

Name=Search
rename "s/^Name/$Name/" *
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top