Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find if filename contains a certain string in bash script

Tags:

bash

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.

like image 627
katiayx Avatar asked May 13 '18 22:05

katiayx


2 Answers

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
like image 100
Kusalananda Avatar answered Oct 07 '22 12:10

Kusalananda


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?

like image 44
Jens Avatar answered Oct 07 '22 10:10

Jens