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

时间:2015-07-13 11:23:34

标签: arrays regex bash

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

我不能让数组只打印正则表达式搜索术语。

format.js

输入: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

1 个答案:

答案 0 :(得分:2)

通过运行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