【问题标题】:How to match file extension in bash? [duplicate]如何匹配bash中的文件扩展名? [复制]
【发布时间】:2019-01-19 08:34:10
【问题描述】:

我只想在文件名以.request 结尾时调用函数,但如果request 是子字符串,它会以某种方式调用该函数。

我marked with red and green导入的部分,右边是输出

for file in ${filesOrDir[*]}; do    
    if [[ -f "$file" ]]; then
        if [[ "$file"=*[".request"] ]]; then
            # Enters here when .request is a substring.
        fi
    fi
    if [[ -d "$file" ]]; then
            # ... some logics       
    fi
done

【问题讨论】:

  • 图中有截图
  • 提供代码
  • [[ $file = *.request ]] ?
  • 更好还是我应该把整个脚本?

标签: string bash shell string-matching


【解决方案1】:

尝试使用:[[ $file == *.request ]]

handle-request.sh 是一个检查文件名的帮助脚本。

handle-request.sh:

while IFS='' read -r line || [[ -n "$line" ]]; do
    if [[ $line == *.request ]]; then
        echo $line
    fi
done < "$1"

解释: reference

IFS=''(或 IFS=)防止前导/尾随空格被修剪。

-r 防止反斜杠转义被解释。

|| [[ -n $line ]] 防止最后一行不以 \n 结尾时被忽略(因为 read 在遇到 EOF 时返回非零退出代码)。

输入文件:

hello.request
.request.hello
file name with space.request

输出:

hello.request
file name with space.request

【讨论】:

  • 祝你好运
  • 谢谢,这是我第二次了……问题是如果文件名中有空格,上面的代码是否也有效?
  • 我添加了带空格的附加输入
  • 选择答案投票下的V,使其变为绿色
猜你喜欢
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多