【问题标题】:Using variables with GREP in Bash script在 Bash 脚本中使用带有 GREP 的变量
【发布时间】:2022-10-17 01:06:23
【问题描述】:

我一直在寻找一个有效的答案,但我在这里,仍然卡住了。我是 bash 脚本的新手,过去几天一直在努力实现我的目标,但我却失去了理智。

目标:我想运行一个脚本来检查包含昨天日期的目录(日期出现在目录名称中的其他文本之间)。听起来很简单!

到目前为止我所拥有的:

DATE=$(date -d '1 day' +%y%m%d)
ls /path/to/folders > ~/listofdirs.txt
GREPDIR=$(grep $DATE ~/listofdirs.txt)
if [ -d /path/to/folders/$GREPDIR ]; then
  echo "Dir exists!"
  echo "(cat $GREPDIR)"
  exit 1
else
  echo "Nothing found."
fi

Grep 没有找到任何结果,因为我确信 $DATE 没有按我的预期工作。如果我用例如:2022 替换 $DATE,我会得到一个结果。感谢您的任何帮助,指导,建议。

编辑:以下作品:D

#!/usr/bin/env bash
#
dirsIncluding="$(date -d '-1 day' +%Y%m%d)"
dirs="/path/to/dir"
regex="*"
if [[ $(ls -d $dirs/$regex$dirsIncluding$regex 2>/dev/null) ]]; then
        echo "Something found."
        else
        echo "Nothing found."
fi

【问题讨论】:

  • 使用bash -x yourscript 查看它实际执行的跟踪日志。将该日志中的 grep 命令与您知道有效的命令进行比较。
  • 也就是说,要查找具有给定日期范围的文件,您应该使用 find,而不是 grepping ls 的输出。 (一般来说,ls 仅用于交互使用;它根本不应该用于脚本)。
  • 也许您在DATE=$(date -d '1 day' +%y%m%d) 中忘记了ago?因为它明天而不是昨天返回。昨天正确的是DATE=$(date -d '1 day ago' +%y%m%d)

标签: bash date variables grep


【解决方案1】:

我没有看到令人信服的理由使用grep.我会简单地使用一个显式循环:

directories_found=0
for entry in *$(date -d '1 day' +%y%m%d)*
do
  if [[ -d $entry ]]
  then
    ((directories_found++))
  fi
done
echo Number of matching directories: $directories_found 

【讨论】:

    【解决方案2】:

    您可以简单地使用ls -d startsWith* 并检查output is empty 是否如下:

    #!/bin/bash
    
    dirsStartingWith="/path/to/dir/*$(date -d '1 day ago' +%y%m%d)*"
    
    if [[ $(ls -d $dirsStartingWith 2>/dev/null) ]]; then
      echo "there are folders starting with $dirsStartingWith"
      #ls -d $dirsStartingWith    # to test output
    else
        echo "no folders starting with $dirsStartingWith found"
    fi
    

    附:您也可以使用find,但我认为ls 应该足够了,因为date 包含在文件夹名称中。

    【讨论】:

    • 我得到了它的工作,但由于日期不在文件夹名称的开头或结尾,我必须包括基本的正则表达式:#!/usr/bin/env bashdirsIncluding="$(date -d '-1 day' +%Y%m%d)"dirs="/path/to/dir"regex="*"regex="*"regex="*"echo $dirs/$regex$dirsIncluding$regex987654332@echo "Something found"`否则`echo "Nothing found."fi谢谢!!
    • 您可以直接将* 添加到要分配给dirsStartingWith 变量的表达式的开头,因为它是在文件名中间的匹配日期之后添加的。我已经调整了我的答案。如果答案对您有帮助,请考虑接受并投票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2011-10-25
    • 2016-01-01
    • 2023-03-30
    • 2023-03-30
    相关资源
    最近更新 更多