在bash中多个目录中有空格的列表文件中搜索子字符串

问题描述 投票:0回答:1

我想创建一个脚本,该脚本循环访问数组中的多个目录,如果其中的文件(不在黑名单中)早于特定时间段,则将其删除。问题是,当尝试列出目录中包含空格的文件时,任何类型的字符串比较(grep -q还是通配符)均不起作用(因此我更改了$IFS值以遍历它们)该脚本不可用。当然,列入黑名单的字符串中也可以有空格。

这是我到目前为止写的内容:

#!/bin/bash

declare -a dirs=(~/path/to/dir1/* ~/path/to/dir2/*)
declare -a blacklist=("file number 1" "file number 2" "file number 3")


saveifs=$IFS
IFS=$'\n'

echo "Starting the autocleaner..."

for dirname in "${dirs[@]}"; do
        for filename in $(ls "$dirname"); do
                for excluded in ${blacklist[@]}; do
                        if [ -e $filename ]; then
                                if echo "$filename" | grep -q "$excluded"; then
                                # if [[ "$filename" == *"$excluded"* ]]; then
                                        :
                                else
                                        if test `find "$filename" -mtime +1`; then
                                                # rm -f $filename
                                                echo "File $filename removed."
                                        else
                                                echo "File $filename is up-to-date and doesn't need to be removed."
                                        fi
                                fi
                        else
                                :
                        fi
                done
        done
done

IFS=$saveifs

我如何使比较实际起作用?

arrays string bash search substring
1个回答
0
投票

您是否尝试过使用单个方括号[ ... ]作为比较线?了解here[ ... ]之间的差异[[ ... ]]可能会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.