Warm tip: This article is reproduced from serverfault.com, please click

how to know if the file is txt in linux

发布于 2020-11-28 14:29:18

I have a code where I need to delete all the .txt files in the main directory.

I have done a loop and in the loop there is if command:

if [ -f $file] 
then 
fi 

now I need another if command where I check if the file is .txt or not.

Questioner
ella
Viewed
0
Nick Ewins 2020-11-29 01:38:53

What about something like this, where the script determines the file type?

filename=testfile
fileType=$(file $filename | cut -d" " -f2)
  if [[ $fileType = "ASCII" ]]
    then
      echo "$filname is a test file"
    else
      echo "$filename is a $fileType file, not a text file"
  fi