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

后端 未结 9 807
不思量自难忘°
不思量自难忘° 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 05:49

    You could also do:

       if [ "${FILE##*.}" = "txt" ]; then
           # operation for txt files here
       fi
    
    0 讨论(0)
  • 2020-12-04 05:51

    I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:

    #!/bin/bash
    # flvcache script
    
    CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
    OUTPUTDIR=~/Videos/flvs
    MINFILESIZE=2M
    
    for f in `find $CACHE -size +$MINFILESIZE`
    do
        a=$(file $f | cut -f2 -d ' ')
        o=$(basename $f)
        if [ "$a" = "Macromedia" ]
            then
                cp "$f" "$OUTPUTDIR/$o"
        fi
    done
    
    nautilus  "$OUTPUTDIR"&
    

    It uses similar ideas to those presented here, hope this is helpful to someone.

    0 讨论(0)
  • 2020-12-04 05:51

    I guess that '$PATH_TO_SOMEWHERE'is something like '<directory>/*'.

    In this case, I would change the code to:

    find <directory> -maxdepth 1 -type d -exec ... \;
    find <directory> -maxdepth 1 -type f -name "*.txt" -exec ... \;
    

    If you want to do something more complicated with the directory and text file names, you could:

    find <directory> -maxdepth 1 -type d | while read dir; do echo $dir; ...; done
    find <directory> -maxdepth 1 -type f -name "*.txt" | while read txtfile; do echo $txtfile; ...; done
    

    If you have spaces in your file names, you could:

    find <directory> -maxdepth 1 -type d | xargs ...
    find <directory> -maxdepth 1 -type f -name "*.txt" | xargs ...
    
    0 讨论(0)
  • 2020-12-04 05:53

    I think you want to say "Are the last four characters of $file equal to .txt?" If so, you can use the following:

    if [ ${file: -4} == ".txt" ]
    

    Note that the space between file: and -4 is required, as the ':-' modifier means something different.

    0 讨论(0)
  • 2020-12-04 05:55

    You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

    file -ib "$file"
    

    Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.

    0 讨论(0)
  • 2020-12-04 05:56

    You can use the "file" command if you actually want to find out information about the file rather than rely on the extensions.

    If you feel comfortable with using the extension you can use grep to see if it matches.

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