如何在linux中创建一个脚本以删除目录中的所有文件,期望仅保留5个文件

发布于 2025-02-11 06:33:24 字数 67 浏览 3 评论 0原文

如何在Linux中创建一个脚本以从目录条件删除所有文件: - 如果在目录中仅保留5个文件,则不应从该目录中删除任何文件。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

春夜浅 2025-02-18 06:33:24
#! /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
#! /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
画离情绘悲伤 2025-02-18 06:33:24

为了解决该问题,请在for-loop之前的文件名更改设置“ 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"

to fix the problem with spaces in filenames change setting of 'IFS' shell variable before the for-loop:

#! /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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文