问题
I am trying to rename a few directories that contain "Fever" to contain "Malaria" instead. The instruction is to do it without sed or rename. So far, my errors include mostly lines like
mv: cannot stat ‘retest\nretest/Section-01\nretest/Section-02\nretest/Section-03\nretest/Section-04’: No such file or directory
.
The best my code have done is rename directories in the first level.
Here's my directory structure:
Fever-A/Malaria-A-A
Fever-B/Fever-B-A
Fever-B/Fever-B-B
Fever-C/Malaria-A
Fever-C/Fever-C-A
Fever-C/Fever-C-B
Fever-C/Fever-C-C-C
Fever-D/Malaria-A
Fever-D/Malaria-B
The code I have so far is :
#!/bin/bash
# Access directory
#cd $1
# Find all subdirectories in $1 and load up array
all=($(find $1 -type d))
#echo ${all[@]}
# Loop through directories above
for dir in ${all[@]}
do
# echo "$dir"
cd $dir
# List files with "Section" in name
subdir=(:"Section*")
# A second loop for directories in each dir with "Section*"
for item in ${subdir[@]}
do
echo $item
echo "--------------------"
# Rename operation
mv $item ${item//Fever/Malaria}
done
cd $1
done
Another approach I've considered is using a function like so, but it's not working either: #!/bin/bash
rename(){
old_names=($(find $1 -maxdepth 1 -type d))
for item in ${old_names[@]}
do
if [[ $item = *Section* ]]; then
new_name=${item//Fever/Malaria}
mv $item $new_name
elif [[ $1 != $item ]]; then
rename $item
fi
rename $1
done
}
rename $1
回答1:
Below script will do what you're looking for :
#/bin/bash
renamer(){
dirname="${1##*/}"
dirname="${dirname//fever/malaria}"
basedir="${1%/*}"
mv "$1" "${basedir}/${dirname}"
}
export -f renamer
find /path/to/start/search/from -depth -type d -name "*fever*" -exec bash -c 'renamer "$1"' _ {} \;
See it action
$ tree .
.
|-- feverparent
| |-- feverchild1
| | `-- feverish_child
| | `-- totally_fever
| `-- feverchild2
| `-- feverchild2_has_a_fever_child
`-- myscript
6 directories, 1 file
$ ./myscript
$ tree .
.
|-- malariaparent
| |-- malariachild1
| | `-- malariaish_child
| | `-- totally_malaria
| `-- malariachild2
| `-- malariachild2_has_a_malaria_child
`-- myscript
6 directories, 1 file
Notes
find
manpage says-depth Process each directory's contents before the directory itself.
The -delete action also implies -depth.See shell [ parameter expansion ] to understand what is being done inside my function
renamer
.
来源:https://stackoverflow.com/questions/38671326/is-there-a-way-to-rename-directories-recursively-without-using-sed-or-rename