如何在不知道扩展名的情况下查找文件?

时间:2021-06-22 14:20:59

标签: bash

目前我正在编写一个脚本,我需要在不知道文件扩展名的情况下检查某个目录中是否存在某个文件。我试过这个:

if [[ -f "$2"* ]]

但这没有用。有谁知道我该怎么做?

3 个答案:

答案 0 :(得分:1)

-f 需要一个参数,而 AFIK 无论如何都不会在此上下文中获得文件名扩展。

虽然很麻烦,但我能想到的最好的方法是生成一个包含所有匹配文件名的数组,即

shopt -s nullglob
files=( "$2".* )

并测试数组的大小。如果它大于 1,则您有多个候选。即

if (( ${#files[*]} > 1 ))
then
  ....
fi

如果大小为 1,则 ${files[0]} 为您提供所需的大小。如果大小为 0(只有打开 nullglob 时才会发生),则没有文件匹配。

如果您不再需要它,请不要忘记在之后重置 nullglob

答案 1 :(得分:1)

在 shell 中,您必须迭代每个文件通配模式的匹配并单独测试每个匹配。

以下是使用标准 POSIX shell 语法的方法:

#!/usr/bin/env sh

# Boolean flag to check if a file match was found
found_flag=0

# Iterate all matches
for match in "$2."*; do

  # In shell, when no match is found, the pattern itself is returned.
  # To exclude the pattern, check a file of this name actually exists
  # and is an actual file
  if [ -f "$match" ]; then
    found_flag=1
    printf 'Found file: %s\n' "$match"
  fi
done
if [ $found_flag -eq 0 ]; then
  printf 'No file matching: %s.*\n' "$2" >&2
  exit 1
fi

答案 2 :(得分:0)

您可以使用find

find ./ -name "<filename>.*" -exec <do_something> {} \;

<filename> 是没有扩展名的文件名,do_something 是您要启动的命令,{} 是文件名的占位符。

相关问题