katiayx
katiayx

Reputation: 241

find if filename contains a certain string in bash script

I have a bunch of output files in a directory, such as: a.out, b.out c.out, etc.

I want to search through the output files and if the output file name contains a certain string (such as "a"), then it will print the corresponding output file "a.out" to screen.

After I cd-ed into the output files directory, here's my code:

OUT_FILE="*.out"
OT=$OUT_FILE
STRING="a"

for file in "$OT";do
  if [[$file == *"$STRING"*]];then
    echo $file
  fi
done

The error I received is [[*.out: command not found. It looks like $file is interpreted as $OT, not as individual files that matches $OT.

But when I removed the if statement and just did a for-loop to echo each $file, the output gave me all the files that ended with .out.

Would love some help to understand what I did wrong. Thanks in advance.

Upvotes: 21

Views: 63633

Answers (2)

Jens
Jens

Reputation: 72639

Without bashisms like [[ (works in any Bourne-heritage shell) and blindingly fast since it does not fork any utility program:

for file in *.out; do
  case $file in
    (*a*) printf '%s\n' "$file";;
  esac
done

If you want you can replace (*a*) with (*$STRING*).

Alternative if you have a find that understands -maxdepth 1:

find . -maxdepth 1 -name \*"$STRING"\*.out

PS: Your question is a bit unclear. The code you posted tests for a in the file name (and so does my code). But your text suggests you want to search for a in the file contents. Which is it? Can you clarify?

Upvotes: 7

Kusalananda
Kusalananda

Reputation: 15613

You need space after [[ and before ]]:

for file in *.out;do
  if [[ "$file" == *"$STRING"* ]];then
    printf '%s\n' "$file"
  fi
done

or just

for file in *"$STRING"*.out; do
    printf '%s\n' "$file"
done

or

printf '%s\n' *"$STRING"*.out

Upvotes: 25

Related Questions