【问题标题】:How to concat string and variable with wild card in shell script如何在 shell 脚本中使用通配符连接字符串和变量
【发布时间】:2021-05-25 20:36:34
【问题描述】:

我正在使用 Amazon Centos 服务器,我想使用 shell 脚本检查文件是否存在。

我有一个目录位置和文件名格式。

我的代码:

yesterdaydate= date -d '-1 day' '+%Y%m%d'
echo $yesterdaydate
Filetemp='/data/ftp/vendor/processed/ccs_'
Filetemp=$Filetemp$yesterdaydate
echo $Filetemp

预期的最终结果应该是这样的/data/ftp/vendor/processed/ccs_20210221_171503_itemsku.xml

当前结果:/data/ftp/corecentric/processed/ccs_

我想要像Filetemp_yesterdaydate_wildcard(*)_itemsku.xml这样的格式

通配符(*)用于文件创建的时间变化。

我怎样才能做到这一点?

【问题讨论】:

    标签: bash shell centos sh


    【解决方案1】:

    只要不引用通配符,Glob(= 通配符)就可以很好地处理变量。
    这里我们使用数组和 bash 的nullglob 选项来统计找到的文件数。

    #! /bin/bash
    shopt -s nullglob
    yesterday=$(date -d '-1 day' '+%Y%m%d')
    files=(/data/ftp/vendor/processed/ccs_"$yesterday"_*_itemsku.xml)
    if (( "${#files[@]}" > 0 )); then
       echo "Found the following ${#files[@]} file(s)"
       printf %s\\n "${files[@]}"
    else
       echo "Found nothing"
    fi
    

    请注意,如果有这样的文件,这也将匹配 ...20210222_something that is not a time string_itemsku.xml。如果是这种情况,您可以将 glob * 更改为 [0-2][0-9][0-5][0-9][0-5][0-9]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      • 2019-01-08
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      相关资源
      最近更新 更多