Shell Geek: Rename Multiple Files At Once Shell Geek: перейменування декількох файлів одночасно
Let's say you have a directory with hundreds of files with the wrong file names, and you'd like to replace every filename containing test with prod . Скажімо, у вас є каталог з сотнями файлів з неправильними іменами файлів, і ви хочете замінити кожне ім'я файлу, що містить тест з Prod. (this is a contrived example). (це надуманий приклад). We can easily do this with the “for” command in bash, combined with a little bit of bash goodness. Ми легко можемо зробити це за допомогою "для" команди у Bash, в поєднанні з трохи Bash добро. Today we'll learn how to replace text in a variable in a for loop. Сьогодні ми дізнаємося, як замінити текст у змінну в циклі.
The “for” command works like this: "За" команда працює таким чином:
for var in <files>;do <command> $var;done для VAR в <files>; робити <command> $ VAR; зробити
You can replace <files> with any file match pattern, such as * or *.txt, and you can replace <command> with any linux command. Ви можете замінити <files> з будь-який шаблон файлу збігаються, наприклад, * або *. TXT, і ви можете замінити <command> Linux з будь-якою командою. The command will be run in sequence on each of the files matched by the file match pattern. Команда буде виконуватися послідовно на кожному з файлів супроводжується шаблоном файлу.
This is where the bash variable handling makes it even more interesting. Ось де Bash змінних робить його ще більш цікавим. Instead of just doing something like “mv $var”, we can replace text in the filename using this syntax: Замість того, щоб просто робити щось на зразок "MV $ Var", ми можемо замінити текст у файл, використовуючи наступний синтаксис:
${var/originaltext/replacetext} $ (VAR / originaltext / ReplaceText)
So now, if we run this command on our directory: Так що тепер, якщо ми запустимо цю команду на наш каталог:
for f in *;do mv $f ${f/test/prod};done Р в *; робити М.В. $ F $ (F / Test / Prod); зробити
For each file matched by *, bash will execute a command similar to this: Для кожного файлу супроводжується *, Bash виконати команду, подібну до цієї:
mv test.config prod.config М. В. test.config prod.config
I've found that knowledge of the shell is invaluable when administering servers or just for managing your file collection, and has saved me hours of what would have otherwise been manual work. Я виявив, що знання оболонки має неоціненне значення при адмініструванні сервера або просто для управління набором файлів, і врятував мені годинник, що б у противному випадку були ручної роботи.
And yes, I realize there are a number of tools that can accomplish renaming of multiple files. І так, я розумію, існує цілий ряд інструментів, які можуть виконати перейменування декількох файлів.

Daily Email Updates Email Щоденні оновлення
You can get our how-to articles in your inbox each day for free. Ви можете отримати наші довідкові статті у Вашу поштову скриньку щодня безкоштовно. Just enter your name and email below: Просто введіть ваші ім'я та адресу електронної пошти нижче:



thanks, really nice article, it has saved me some time and it will alot more in the future. Спасибі, дуже приємно стати, вона врятувала мене деякий час, і воно буде набагато більше в майбутньому.
Hey… thanks a lot for this article … this really saved lot of my time …. Ей ... Величезне спасибі за цю статтю ... це дійсно збережених багато часу .... i reallly appreciate it … Я reallly оцінять ...
You are a GOD. Ви Бог. This is what I have been looking for. Це те, що я шукала. Can this functionality exist outside of “for loop”. Чи може ця функція існує поза "циклі". How good is Bash's regex engine? Наскільки добре Regex двигун в Bash? Is it full featured? Це повнофункціональні?
“ls [^a}*” finds all files that begin with anything BUT letter “a”. "LS [^) *" знаходить всі файли, які починаються з букви, але нічого "А". What else is possible? Що ще можна?
This is great, and I use it frequently for changing filename suffixes. Це здорово, і я використовую його часто для зміни імені файлу суфікс.
However, if you are stuck with filenames that contain spaces, you need to quote around the variable and the replacement expression, as shown in the example below. Однак, якщо ви застрягли в імена файлів, що містять пробіли, необхідно привести в околицях змінних і заміна вирази, як показано в наступному прикладі.
for f in *;do mv “$f” “${f/\.oga/.ogg}”;done Р в *; робити MV "$ F" "$ (F / \. Oga /. Ogg)"; зробити
renaming multiple files at once перейменування декількох файлів одночасно