1

I have a string (a filename, actually) that I want to test whether they contain a character:

NEEDLE="-"
for file in mydirectory/*
do
   if [NEEDLE IS FOUND IN STRING]
   then
       # do something
   else
       # do something else
   fi
done

Basically this is the same question as String contains in Bash, except for dash instead of bash (ideally shell-neutral, which is usually the case with dash-code anyway)

The [[ operator does not exist in dash, therefore the answer to that question does not work.

Community
  • 1
  • 1
Roland Seuhs
  • 1,878
  • 4
  • 27
  • 51

2 Answers2

2

use a case statement, no need to spawn an external program:

NEEDLE="-"
for file in mydirectory/*; do
    case "$file" in
        *"$NEEDLE"*) echo "do something" ;;
        *) echo "do something else" ;;
    esac
done
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

You can just use grep -q inside for loop:

NEEDLE="-"
for file in mydirectory/*; do
    if grep -q "$NEEDLE" "$file"; then
       echo "do something"
    else
       echo "do something else"
    fi
done
anubhava
  • 761,203
  • 64
  • 569
  • 643