如何在shell脚本中使用通配符连接字符串和变量



我正在使用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

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

我怎样才能做到这一点?

Globs (= wildcards)可以很好地处理变量,只要你不引用通配符。
这里我们使用数组和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]

最新更新