I have to sort and print all the file names of files that are ASCII text from a given folder. I made this so far but the file names are printed even if they are PNG images.
#!/bin/bash
for f in $1/*
do
nume=$(basename $f)
if [ 'file $nume'=="$1/$nume: ASCII text" ]; then
echo $nume
fi
done
Can someone please explain what`s wrong with my code?
[
wants just an equal sign, not two, and it needs to be separated by spaces (see help test
):
[ 'file $nume' = "$1/$nume: ASCII text" ]
You need $(...)
to get the output from a command:
[ "$(file $nume)" = "$1/$nume: ASCII text" ]
Why are you using basename
? file
is not going to find your file if you don't give it the whole path:
for f in $1/*
do
if [ "$(file $f)" = "$f: ASCII text" ]; then
echo $f
fi
done
Always quote your expansions. Quoting can save you a lot of headaches:
for f in "$1"/*
do
if [ "$(file "$f")" = "$f: ASCII text" ]; then
echo "$f"
fi
done
(Optional) Personally, I'd take advantage of [[
and regex matching:
if [[ "$(file "$f")" =~ ': ASCII text'$ ]]; then