我搞砸了一个备份脚本,现在很多文件都是 File1.txt/File1.txt。我该如何删除目录并保留文件?操作系统是 Ubuntu

我搞砸了一个备份脚本,现在很多文件都是 File1.txt/File1.txt。我该如何删除目录并保留文件?操作系统是 Ubuntu

例如,我有:

~/backup/File1.txt/File1.txt

但我想要的是:

~/backup/File1.txt

目录 File1.txt 中除了文件 File1.txt 之外是空的。为了手动解决该问题,我已将 File1.txt 移动到 File1 文件夹,然后 mv File1.txt ../,然后删除 File1 文件夹,但我想自动执行该操作。

答案1

有多种方法。例如:

    cd ~/backup # Move to the backup folder
    TEMPDIR=$HOME/backup-tmp # Temporary directory
    mkdir -p "$TEMPDIR" # Ensure it exists
    for contents in *; do # Iterate all the contents of the folder, which are folders but should be files (note: we assume none of them start with .)
       mv "$contents/$contents" "$TEMPDIR" # Move the subfile to the temporary folder
       rmdir "$contents" # Now we can remove the empty dir
       mv "$TEMPDIR/$contents" .  # Move back to the backup dir
    done
    rmdir "$TEMPDIR" # We are done with the temporary directory

答案2

正如@Angel所说,有很多方法。我认为这个太复杂了。这是一个更简单的版本。

mv ~/backup ~/backup-wrong   
mkdir ~/backup
mv ~/backup-wrong/*/*.txt ~/backup
rm -r ~backup-wrong

上面的关键是第 3 行,它将 ~/backup-wrong 的任何子目录中所有以 .txt 结尾的文件匹配到新的备份目录。

答案3

mkdir ~/backup2
find ~/backup -type f -print -exec mv {} ~/backup2 \;
rm -r ~/backup
mv ~/backup2 ~/backup

相关内容