在bash中,如何检查文件名是否以某个字符串开头并以另一个字符串结尾?

时间:2017-11-06 20:48:21

标签: bash

我想要运行测试的文件名的哈希值。例如:

index.html

变为

index-12345678k9.html

我正在寻找类似于以下内容的bash脚本:

if [ "index(-dynamically created hash).html file exists in directory" ]
then
  echo 'passed'
else
  echo 'not passed'
fi

2 个答案:

答案 0 :(得分:3)

检查特定文件是否匹配

shopt -s extglob   # enable "extended globbing" syntax

check_candidate() {
  local pattern=$1 candidate=$2 ext basename
  if [[ $pattern = *.* ]]; then                 # if our input file has an extension...
    ext=${pattern##*.}                          # extract that extension
    basename=${pattern%.$ext}                   # and likewise the basename
    [[ $candidate = "$basename"?(-*)".$ext" ]]  # ...checking if our candidate matches
  else
    [[ $candidate = "$basename"?(-*) ]]
  fi
}
给定以下任何一项

...将返回true:

check_candidate index      index-1234
check_candidate index.html index.html
check_candidate index.html index-1234.html
check_candidate index.html index-foo.html

但是假的,给出以下任何一个:

check_candidate index.html notindex-4321.html
check_candidate index.html index-abcd.txt

检查是否存在匹配文件

如果您的目标是检查是否存在任何文件,则会显示如下:

shopt -s extglob  # enable ?(...) glob syntax

check_candidate() {
  local pattern=$1
  local candidate=$2
  if [[ $pattern = *.* ]]; then
    ext=${pattern##*.}
    basename=${pattern%.$ext}
    set -- "$basename"?(-*)".$ext"   # replace argument list with files matching glob
  else
    set -- "$basename"?(-*)          # likewise, no-extension version
  fi

  [[ -e "$1" || -L "$1" ]]        # true if our argument list has at least one element
                                  # and that element is the name of a file that exists.
}

...如果当前目录中存在 check_candidate index.html或任何匹配index.html的文件,index-something.html将返回true。

答案 1 :(得分:0)

这样的事情会起作用吗?

{{1}}