繁体   English   中英

BASH-在数组中查找正则表达式,打印找到的数组项

[英]BASH - find regex in array, print found array items

我已经在这里测试过正则表达式: http : //regexr.com/3bchs

我无法获取仅打印正则表达式搜索项的数组。

files=(`ls $BACKUPDIR`)
daterange='(2015\-06\-)[0-9]+\s?'

for i in "${files[@]}"
do
        if [[ "$files[$i]" =~ $daterange ]];
         then
                 echo $i
         fi
done

输入: 2015-06-06 2015-06-13 2015-06-20 2015-06-27 2015-07-04 2015-07-11

输出:

2015-06-06 
2015-06-13 
2015-06-20 
2015-06-27 
2015-07-04 
2015-07-11

通过运行bash -vx <script>我发现它正在编译的文件是错误的。 我需要将$files[$i]更改为$i

$files[$i] = 2015-06-06 [2015-06-06]

感谢Etan Reisner的评论,我的答案得到了进一步的改善。 通过不解析ls输出。

参考: https : //stackoverflow.com/a/11584156/3371795

#!/bin/bash

# Enable special handling to prevent expansion to a
# literal '/example/backups/*' when no matches are found. 
shopt -s nullglob

        # Variables
        YEAR=`date +%Y`
        MONTH=`date +%m`

        DIR=(/home/user/backups/backup.weekly/*)

        # REGEX - Get curent month
        DATE_RANGE='('$YEAR'\-'$MONTH'\-)[0-9]+\s?'


# Loop through dir
for i in "${DIR[@]}";
do
        # Compare dir name with date range
        if [[ "$i" =~ $DATE_RANGE ]];
        then
                # I have no idea what this is, works fine without it.
                [[ -d "$i" ]] 

                # Echo found dirs
                echo "$i"
        fi
done

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM