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,708
  • 4
  • 23
  • 47

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
  • 223,850
  • 36
  • 205
  • 328
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
  • 713,503
  • 59
  • 514
  • 593