How to check the extension of a filename in a bash script?

后端 未结 9 808
不思量自难忘°
不思量自难忘° 2020-12-04 05:33

I am writing a nightly build script in bash.
Everything is fine and dandy except for one little snag:


#!/bin/bash

for file in \"$PATH_TO_SOMEWHERE\"; d         


        
相关标签:
9条回答
  • 2020-12-04 06:04

    Similar to 'file', use the slightly simpler 'mimetype -b' which will work no matter the file extension.

    if [ $(mimetype -b "$MyFile") == "text/plain" ]
    then
      echo "this is a text file"
    fi
    

    Edit: you may need to install libfile-mimeinfo-perl on your system if mimetype is not available

    0 讨论(0)
  • 2020-12-04 06:06

    The correct answer on how to take the extension available in a filename in linux is:

    ${filename##*\.} 
    

    Example of printing all file extensions in a directory

    for fname in $(find . -maxdepth 1 -type f) # only regular file in the current dir
        do  echo ${fname##*\.} #print extensions 
    done
    
    0 讨论(0)
  • 2020-12-04 06:12

    Make

    if [ "$file" == "*.txt" ]
    

    like this:

    if [[ $file == *.txt ]]
    

    That is, double brackets and no quotes.

    The right side of == is a shell pattern. If you need a regular expression, use =~ then.

    0 讨论(0)
提交回复
热议问题