gad*_*tmo 2 command-line rm macos
如何删除目录但不删除其中的文件?我尝试了以下方法:
rm -di /Users/arthur/Desktop/MyFolder
remove /Users/arthur/Desktop/MyFolder? y
rm: /Users/arthur/Desktop/MyFolder: Directory not empty
Run Code Online (Sandbox Code Playgroud)
我在 Mac 上。顺便说一句,我想自动执行此操作。
只需将文件向上移动一个目录,然后将其删除。这将保留包含的文件/文件夹层次结构。
mv ~/Desktop/MyFolder/* ~/Desktop/MyFolder/..
rmdir ~/Desktop/MyFolder
Run Code Online (Sandbox Code Playgroud)
您可以将其放入您定义的 shell 函数中~/.bash_profile:
function rmd () {
if [ -d "$1" ]; then
mv "$1"/* "$1"/..
rmdir "$1"
else
echo "$1 is not a directory"
fi
}
Run Code Online (Sandbox Code Playgroud)
如前所述,这只会删除父文件夹,保持子级层次结构完整。
如果要递归删除所有文件夹并仅保留文件,请改用以下命令:
function rmdr () {
if [ -d "$1" ]; then
p="$1"/..
find "$1" -type f -exec mv '{}' "$p" \;
rm -rf "$1"
else
echo "$1 is not a directory"
fi
}
Run Code Online (Sandbox Code Playgroud)
请注意,这会覆盖具有重复名称的文件。
最后,如果你想保留重复的文件,你可以检查它们是否已经存在。在这种情况下,我们将在它们前面加上一个随机数字字符串。当然,可能有比这更复杂的方法,但你可以看到这是怎么回事。
function rmdr () {
if [ -d "$1" ]; then
p="$1"/..
# loop through all files
while IFS= read -r -d '' file; do
filename=$(basename "$file")
# if it already exists, prefix with random number
if [ -f "$p/$filename" ]; then
mv "$file" "$p/$RANDOM-$filename"
# if it doesn't exist, just move
else
mv "$file" "$p"
fi
done < <(find "$1" -type f -print0)
# remove parent directory
rm -rf "$1"
else
echo "$1 is not a directory"
fi
}
Run Code Online (Sandbox Code Playgroud)
循环通过find输出解释here。
| 归档时间: |
|
| 查看次数: |
284 次 |
| 最近记录: |