0

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.

Alexandre Juma
  • 3,128
  • 1
  • 20
  • 46
ella
  • 55
  • 6
  • 7
    Text is in the eye of the beholder – stark Nov 28 '20 at 14:33
  • 1
    Duplicate: https://stackoverflow.com/questions/407184/how-to-check-the-extension-of-a-filename-in-a-bash-script – Alexandre Juma Nov 28 '20 at 14:33
  • when we make a new file – ella Nov 28 '20 at 14:48
  • like touch j , j is a text file or it is only a text file if we do it like this: touch j.txt – ella Nov 28 '20 at 14:48
  • because when I tried to see if it see a txt file it wasn't – ella Nov 28 '20 at 14:49
  • 2
    The command `touch` is used to update the timestamps in an specific Inode. If the Inode does not exist yet, it will be created. Just because you updated the access time of a filesystem object does not mean, that you created any specific kind of file at all. You only created implicitly a generic object in the filesystem. – mju Nov 28 '20 at 15:47

1 Answers1

1

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
Nick Ewins
  • 39
  • 2