gpt4 book ai didi

bash - 展平目录结构并保留重复文件

转载 作者:行者123 更新时间:2023-11-29 09:16:10 24 4
gpt4 key购买 nike

我的目录结构如下所示:

foo
├── 1.txt
├── 2.txt
├── 3.txt
├── 4.txt
└── bar
├── 1.txt
├── 2.txt
└── 5.txt

我想展平这个目录结构,以便所有文件都在 foo 目录中并保留重复文件:

foo
├── 1.txt
├── 2.txt
├── 3.txt
├── 4.txt
├── bar-1.txt
├── bar-2.txt
└── bar-5.txt

重命名的重复文件名无关紧要。

我可以使用简单的 Unix 单行代码或简单的 shell 脚本来执行此操作吗?

最佳答案

这应该有效:

target="/tmp/target"; find . -type f | while read line; do outbn="$(basename "$line")"; while true; do if [[ -e "$target/$outbn" ]]; then outbn="z-$outbn"; else break; fi; done; cp "$line" "$target/$outbn"; done

格式化为非一行:

target="/tmp/target"
find . -type f | while read line; do
outbn="$(basename "$line")"
while true; do
if [[ -e "$target/$outbn" ]]; then
outbn="z-$outbn"
else
break
fi
done
cp "$line" "$target/$outbn"
done

一定要在你的案例中从 foo 目录运行它,并将 $target 变量设置为目标目录。

例子:

$ find foofoofoo/1foo/2foo/3foo/4foo/barfoo/bar/1foo/bar/2foo/bar/3foo/bar/4foo/bar/5
$ cd foo/
$ target="/tmp/target"; find . -type f | while read line; do outbn="$(basename "$line")"; while true; do if [[ -e "$target/$outbn" ]]; then outbn="z-$outbn"; else break; fi; done; cp "$line" "$target/$outbn"; done

然后

$ find $target/tmp/target/tmp/target/1/tmp/target/2/tmp/target/3/tmp/target/4/tmp/target/5/tmp/target/z-1/tmp/target/z-2/tmp/target/z-3/tmp/target/z-4

关于bash - 展平目录结构并保留重复文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20799905/

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