Skip to content
Advertisement

how to know if the file is txt in linux

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement