Subscribe to How-To Geek Підписатись на How-To Geek

Important! This is an automatic machine translated page. If you can read english, you should Click Here to read the original English version of the article.

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. І так, я розумію, існує цілий ряд інструментів, які можуть виконати перейменування декількох файлів.

This article was originally written on 07/17/07 Tagged with: Ця стаття була спочатку написана на 07/17/07 тегами: Ubuntu Ubuntu

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: Просто введіть ваші ім'я та адресу електронної пошти нижче:


Name: Ім'я:
Email: Електронна пошта:

Comments (5) Коментарі (5)

  1. skeptic Скептик

    thanks, really nice article, it has saved me some time and it will alot more in the future. Спасибі, дуже приємно стати, вона врятувала мене деякий час, і воно буде набагато більше в майбутньому.

  2. sachadon sachadon

    Hey… thanks a lot for this article … this really saved lot of my time …. Ей ... Величезне спасибі за цю статтю ... це дійсно збережених багато часу .... i reallly appreciate it … Я reallly оцінять ...

  3. felipe alvarez Felipe Alvarez

    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? Що ще можна?

  4. Keith Кейт

    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)"; зробити

  5. scripter сценарист

Leave a Comment Залишити коментар




Leave your Залиш свій friendly дружній comment here. коментарі.

If you have a computer help question, Якщо у вас є комп'ютер допоможе питання, click here to leave it on the forums Натисніть тут, щоб залишити його на форумах instead. замість.

Note: Your comment may not show up immediately on the site. Примітка: Ваш коментар може не з'явитися відразу на місці.

Our Friends Наші друзі
Getting Started Приступаючи до роботи


About How-To Geek Про How-To Geek
What Is That Process? Що це за процес?
svchost.exe svchost.exe
jusched.exe jusched.exe
dwm.exe dwm.exe
ctfmon.exe Ctfmon.exe
wmpnetwk.exe wmpnetwk.exe
wmpnscfg.exe wmpnscfg.exe
rundll32.exe rundll32.exe
wfcrun32.exe wfcrun32.exe
Ipoint.exe Ipoint.exe
Itype.exe Itype.exe
Wfica32.exe Wfica32.exe
Mobsync.exe Mobsync.exe
conhost.exe conhost.exe
Dpupdchk.exe Dpupdchk.exe Adobe_Updater.exe Adobe_Updater.exe

Copyright © 2006-2009 HowToGeek.com. Copyright © 2006-2009 HowToGeek.com. All Rights Reserved. Всі права захищені.