gpt4 book ai didi

linux - 使用 bash 中的查找重命名多个级别的目录

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:05 26 4
gpt4 key购买 nike

我正在遍历查找的结果,并且正在更改这些文件夹中的每一个,所以我的问题是当我遇到:/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 选项来查找。这使得它在处理目录本身之前处理目录内容。

关于linux - 使用 bash 中的查找重命名多个级别的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35281532/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com