Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash while read line loop does not print every line in condition

Tags:

bash

awk

I have the following situation:

I have a text file I'm trying to loop so I can know if each line has a match with ".mp3" in this case which is this one:

12 Stones.mp3
randomfile.txt
Aclarion.mp3
ransomwebpage.html
Agents Of The Sun.mp3
randomvideo.mp4

So, I've written the following script to process it:

while read line || [ -n "$line" ]
do
varline=$(awk '/.mp3/{print "yes";next}{print "no"}')
echo $varline
if [ "$varline" == "yes" ]; then
        some-command
    else
         some-command
    fi
done < file.txt

The expected output would be:

yes
no
yes
no
yes
no

Instead, it seems misses the first line and I get the following:

no
yes
no
yes
no
like image 266
Fdonadon Avatar asked Jan 19 '26 22:01

Fdonadon


1 Answers

You really don't need Awk for a simple pattern match if that's all you used it for.

while IFS= read -r line; do
    case $line in
     *.mp3) some-command;,
     *) some-other-command;;
    esac
done <file.txt

If you are using Awk anyway for other reasons, looping the lines in a shell loop is inefficient and very often an antipattern. This doesn't really fix that, but at least avoids executing a new Awk instance on every iteration:

awk '{ print ($0 ~ /\.mp3$/) ? "yes" : no" }' file.txt |
while IFS= read -r whether; do
    case $whether in
     'yes') some-command ;;
     'no') some-other-command;;
    esac
done

If you need the contents of "$line" too, printing that from Awk as well and reading two distinct variables is a trivial change.

I simplified the read expression on the assumption that you can make sure your input file is well-formed separately. If you can't do that, you need to put back the more-complex guard against a missing newline on the last line in the file.

like image 147
tripleee Avatar answered Jan 22 '26 17:01

tripleee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!