1

I'm trying to read a part of a file name to make it in an if .. else statement

for example : file name : foo_bar_test1_example.stat

I want to do a test; if the word : example exists in the file name , then there are some scripts to execute.

Thanks in advance :)

  • I'm new with shell scripting ..is there something wrong with the question ? why Its down voted ? :'( – pietà Mar 1 '16 at 12:48
3

With bash you can do as follows:

#!/bin/bash
#let's look for an a in our handful of files
string="a"
for file in aa ab bb cc dd ad ; do
  #note the placement of the asterisks and the quotes
  #do not swap file and string!
  if [[ "$file" == *"$string"* ]] ; then
     echo "$string in $file"
  else
     echo "no match for $file"
  fi
done

EDIT: simplification with bash's regex matching, as suggested by @JeffSchaller:

if [[ "$file" =~ $string ]] ; then
  • 3
    also with bash, you can use regular expression matching inside [[, such as: if [[ "$file" =~ example ]]; then echo found; else echo not found; fi – Jeff Schaller Mar 1 '16 at 13:41
  • @JeffSchaller pretty good point, I had forgotten about this option. updated – Fiximan Mar 1 '16 at 15:21
  • 1
    Note that they're not specific to bash. The [[ string == pattern ]] comes from ksh and is available in bash, ksh and zsh, [[ string =~ regexp ]] comes from bash and is available in bash, ksh93 and zsh. However note that with bash 3.1 and below and zsh $string would be considered as a regexp. – Stéphane Chazelas Mar 1 '16 at 15:30
5

case is the construct for that in shells of the Bourne family (Bourne, Almquist, ksh, bash, zsh, yash...):

case $file in
  *example*) do-something-for-example "$file";;
  *) do-something-else-if-not "$file";;
esac

In shells of the csh family (csh, tcsh):

switch ($file:q)
  case *example*:
    do-something-with $file:q
    breaksw

  default:
    do-something-else-with $file:q
    breaksw
endsw

In the fish shell:

switch $file
  case '*example*'
    do-something-with $file
  case '*'
    do-something-else-with $file
end

With rc or aganga:

switch ($file) {
  case *example*
    do-something-with $file

  case *
    do-something-else-with $file
}

With es:

if {~ $file *example*} {
  do-something-with $file
} {
  do-something-else-with $file
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.