使用从 bash 中查找在多个级别重命名目录
Renaming directories at multiple levels using find from bash
我正在遍历查找的结果,并且正在更改这些文件夹中的每一个,所以我的问题是当我遇到:
/aaaa/logs/
之后:/aaaa/logs/bbb/logs
,当我尝试 mv /aaaa/logs/bbb/logs /aaaa/log/bbb/log
时找不到该文件夹,因为它已被重命名。即,find
的输出可能报告名称为 /aaaa/logs/bbb/logs
,而脚本先前将输出移动到 /aaaa/log/bbb/
。
简单代码:
#!/bin/bash
script_log="/myPath"
echo "Info" > $script_log
search_names_folders=`find /home/ -type d -name "logs*"`
while read -r line; do
mv $line ${line//logs/log} >>$script_log 2>&1
done <<< "$search_names_folders"
我的解决方案是:
#!/bin/bash
script_log="/myPath"
echo "Info" > $script_log
search_names_folders=`find /home/ -type d -name "logs*"`
while read -r line; do
number_of_occurrences=$(grep -o "logs" <<< "$line" | wc -l)
if [ "$number_of_occurrences" != "1" ]; then
real_path=${line//logs/log} ## get the full path, the suffix will be incorrect
real_path=${real_path%/*} ## get the prefix until the last /
suffix=${line##*/} ## get the real suffix
line=$real_path/$suffix ## add the full correct path to line
mv $line ${line//logs/log} >>$script_log 2>&1
fi
done <<< "$search_names_folders"
但这是个坏主意,有没有人有其他解决方案?
谢谢!
使用 -depth
选项 find
。这使得它在处理目录本身之前处理目录内容。
我正在遍历查找的结果,并且正在更改这些文件夹中的每一个,所以我的问题是当我遇到:
/aaaa/logs/
之后:/aaaa/logs/bbb/logs
,当我尝试 mv /aaaa/logs/bbb/logs /aaaa/log/bbb/log
时找不到该文件夹,因为它已被重命名。即,find
的输出可能报告名称为 /aaaa/logs/bbb/logs
,而脚本先前将输出移动到 /aaaa/log/bbb/
。
简单代码:
#!/bin/bash
script_log="/myPath"
echo "Info" > $script_log
search_names_folders=`find /home/ -type d -name "logs*"`
while read -r line; do
mv $line ${line//logs/log} >>$script_log 2>&1
done <<< "$search_names_folders"
我的解决方案是:
#!/bin/bash
script_log="/myPath"
echo "Info" > $script_log
search_names_folders=`find /home/ -type d -name "logs*"`
while read -r line; do
number_of_occurrences=$(grep -o "logs" <<< "$line" | wc -l)
if [ "$number_of_occurrences" != "1" ]; then
real_path=${line//logs/log} ## get the full path, the suffix will be incorrect
real_path=${real_path%/*} ## get the prefix until the last /
suffix=${line##*/} ## get the real suffix
line=$real_path/$suffix ## add the full correct path to line
mv $line ${line//logs/log} >>$script_log 2>&1
fi
done <<< "$search_names_folders"
但这是个坏主意,有没有人有其他解决方案? 谢谢!
使用 -depth
选项 find
。这使得它在处理目录本身之前处理目录内容。