LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   if file *.txt then do x else if *.mp3 file then do xx (bash) (https://www.linuxquestions.org/questions/linux-newbie-8/if-file-%2A-txt-then-do-x-else-if-%2A-mp3-file-then-do-xx-bash-718058/)

Techno Guy 04-09-2009 05:34 PM

if file *.txt then do x else if *.mp3 file then do xx (bash)
 
So I want to check if there is a file that has an extension of ether .txt or .mp3 and to exicute code if one is found.


Kinda like this: (but this doesn't work for obvious reasons :( )
Code:

for rfile in *.txt *.mp3; do
    if *.txt ; then
        echo here is a txt "$rfile"

        #do stuff
               
               
    elif *.mp3 ; then
              echo  here is mp3 "$rfile"

        #do stuff

    else
        echo other files "$rfile"
    fi
done

Thanks in advanced for any help :)

jschiwal 04-09-2009 05:48 PM

You could break it up into two loops.
Code:

for rfile in *.txt; do
  echo $rfile is a text file
  # do stuff
done

for rfile in *.mp3; do
  echo $rfile is an mp3 file
  #do stuff
done

Another thing you could do is use the find command.
find . -type f -iname "*.txt" -exec <command> \;
find . -type f -iname "*.mp3" -exec <command> \;

Be sure to read through the bash info manual. In particular the section on "test" & "[[" and the section on variable expansion.
also enter "help test" in the shell.

Techno Guy 04-12-2009 07:31 AM

Thanks jschiwal!

Really appreciate your help, I will use the 2 for loops for now.
When I have some more time ill look into the other options for a more permanent solution.

David the H. 04-12-2009 08:52 PM

Try this. Use the for loop to find the files you want, then test them with an if or case statement. I prefer case myself usually. {} can be used to match multiple patterns at once.

Code:

for rfile in *.{txt,mp3}; do

  case rfile in

    *.txt )
      echo $rfile is a text file
      # do stuff
    ;;
    *. mp3 )
      echo $rfile is an mp3 file
      #do stuff
    ;;
  esac
done



All times are GMT -5. The time now is 03:51 AM.