【问题标题】:BASH - find regex in array, print found array itemsBASH - 在数组中查找正则表达式,打印找到的数组项
【发布时间】:2015-07-13 11:23:34
【问题描述】:

我在这里测试了正则表达式: 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] 中的{}。试试${files[$i]}
  • @anubhava 我已经添加了输入
  • 感谢你们,我已经解决了我的问题

标签: arrays regex bash


【解决方案1】:

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

【讨论】:

  • 你不应该是parsing the output from ls。改为在该数组中使用 glob(这可能意味着可能需要去除循环中的路径,但 basenameshell parameter expansion 可以为您做到这一点)。
  • 感谢@EtanReisner,我已经更新了我的答案。有谁知道这是什么“ [[ -d "$i" ]] ”,我在谷歌上找不到任何东西。
  • [[[/test 的特定 bash 版本,语义略有不同。 -d 是“是一个目录”。请注意,在原始文件中它是 [[ -d "$folder" ]] && echo "$folder",所以这是“如果 $folder 是一个目录,则回显 $folder”。 [[ -d "$folder" ]] 本身只返回 true 或 false,因此在您的代码中它什么也不做。
  • 谢谢兄弟,在我的场景中,我在这里看不到它的用途?
  • 按你的方式编写,正如我所说,没有任何目的,因为它只是返回 true 或 false 并且不会影响或打印任何内容。在带有&& 的原始文件中,它导致echo 仅在它返回true 时发生(即文件夹是一个目录)。
猜你喜欢
  • 2021-02-24
  • 1970-01-01
  • 2017-11-05
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2014-06-16
  • 1970-01-01
相关资源
最近更新 更多