简体   繁体   English

如何在 Linux 中创建脚本以删除目录中的所有文件,只剩下 5 个文件

[英]How to create a script in Linux to delete all files from the directory expect only left 5 files

How to create a script in Linux to delete all files from the directory Condition:- If in the directory only 5 files are left then should not delete any files from that directory.如何在 Linux 中创建脚本以删除目录中的所有文件条件:- 如果目录中只剩下 5 个文件,则不应从该目录中删除任何文件。

#! /bin/bash

myPath="/tmp"

myFileList=$(find $myPath -maxdepth 1   -type f)

num=0

for candidate in $myFileList
do
        num=$(($num + 1))

        if [[ $num -le 5 ]]
        then
                echo "do not delete: $num"
                continue
        fi

        echo "number $num: delete $candidate"
        # remove the followong comment sign if you want the script to remove the file
        # rm $candidate
done

to fix the problem with spaces in filenames change setting of 'IFS' shell variable before the for-loop:解决文件名中的空格问题,在 for 循环之前更改 'IFS' shell 变量的设置:

#! /bin/bash

myPath="/tmp"

myFileList=$(find $myPath -maxdepth 1   -type f  -printf "%T@ %p\n" |sort -rn|awk '1 {$1=""; print $0;}')

num=0

OIFS="$IFS"
IFS=$'\n'

for candidate in $myFileList
do
        num=$(($num + 1))

        if [[ $num -le 5 ]]
        then
                echo "do not delete: $num  \"$candidate\""
                continue
        fi

        echo "number $num: delete $candidate"
        # remove the followong comment sign if you want the script to remove the file
        # rm $candidate
done
IFS="$OIFS"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Linux CLI查找一行代码并从特定/目录中的所有文件中删除该行 - How to find a line of code and delete that line from all files in a certain /directory only, using Linux CLI 在Linux终端中,如何删除目录中除一个或两个以外的所有文件 - In Linux terminal, how to delete all files in a directory except one or two 如何删除最近在linux目录中创建的所有文件? - How to delete all files that were recently created in a directory in linux? Linux:如何删除目录本身(不是子目录)内的所有文件(不是目录) - Linux: How to delete all of the files (not directories) inside a directory itself (not childs) 删除linux中目录的所有子目录中的特定文件 - Delete particular files in all subdirectories of a directory in linux Linux:使用Expect脚本压缩所有具有相同后缀的文件 - Linux : Zip all the files with same suffix using expect script 在Linux脚本中,如何删除当前目录中的所有文件和目录? - In a Linux script, how to remove all files & directories but one, in current directory? Linux脚本,用于目录文件 - Linux Script, for on files of a directory 将删除上个月文件的 linux 脚本 - linux script that will delete files from previous month 用于删除目录中所有文件并打印已删除文件计数的Shell脚本 - Shell Script for Delete all files in directory and print count of deleted files
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM