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.
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With