【问题标题】:Search for a substring within listed files with spaces from multiple directories in bash在 bash 中的多个目录中搜索带有空格的列出文件中的子字符串
【发布时间】:2020-07-22 12:02:45
【问题描述】:

我想创建一个脚本,该脚本在数组中循环多个目录,如果其中的文件不在黑名单中,超过某个时间段,则将其删除。问题是任何类型的字符串比较(无论是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】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 2013-06-10
    • 2017-03-03
    相关资源
    最近更新 更多