Я успешно использую следующую простую строку кода, чтобы удалить указанное слово из всех имен файлов в каталоге:
for file in *.* ; do mv "${file}" "${file//UNWANTEDWORD}"; done
Но что я могу добавить к этому коду, чтобы указать только подкаталоги в каталоге, а НЕ файлы?
Итак, перефразирую: я хочу удалить определенное слово из каждого имени подкаталога в каталоге, который содержит как каталоги, так и файлы, и это не влияет на файлы. Есть идеи?
Try:
find ./dir1 -depth -type d -name '*UNWANTEDWORD*' -exec bash -c 'mv "${1}" "${1//UNWANTEDWORD}"' mv {} \;
The above searches recursively through the directory structure. If you want to operate only files in the current directory, .
, then run:
find ./dir1 -maxdepth 1 -depth -type d -name '*UNWANTEDWORD*' -exec bash -c 'mv "${1}" "${1//UNWANTEDWORD}"' mv {} \;
find ./dir1
Start a find
command and tell it which directory to look in. If you want to start with the current directory, replace ./dir1
with .
.
-depth
Search each directory's contents before the directory itself.
-type d
Search only for directories.
-name '*UNWANTEDWORD*'
Limit the search to directory names containing UNWANTEDWORD
. There is no point wasting time on directories that don't have this word.
-exec bash -c 'mv "${1}" "${1//UNWANTEDWORD}"' move {} \;
Run your shell command on each file found.
(In the above, when the shell command is executed, the string move
is assigned to $0
. This is unimportant unless the shell code generates and error in which case the error message use $0
as the script name.)
Note: this assumes that your original glob expression *.*
is correct, i.e. that you wish to loop over directories whose names contain a period character, like foo.bar
You can make the shell glob *.*
match only directories by suffixing it with /
:
for file in *.*/ ; do mv "${file}" "${file//UNWANTEDWORD}"; done
Alternatively, add a simple directory test:
for file in *.* ; do [ -d "$file" ] && mv "${file}" "${file//UNWANTEDWORD}"; done