pyrrhus
pyrrhus

Reputation: 57

How do I read lines from a file in a loop?

my goal is to TTS each line of a text file

First I count the number of lines of my text file:

#!/bin/bash

LINES=$(cat /home/mytext.txt | wc -l)

I want to define a loop:

let "n = $LINES"
while [ $n -ne 0 ]

TTS "the first line"
sleep 5

let "n--"
done
exit

Then the loop repeats to read the next line ...etc, as long as the next line exists.

Upvotes: 0

Views: 94

Answers (1)

user268396
user268396

Reputation: 11976

What you want is to read:

cat /home/mytext.txt |\
while IFS='' read -r CUR_LINE || [ -n "$CUR_LINE" ]; do
   do_something_with "$CUR_LINE"
done

It will: cat your text file, read the next line until no more lines are left and do something with each line. Note, the || [ -n "$CUR_LINE" ] bit is to ensure that if the text file doesn't end with a blank line the while doesn't end with an error state (non-zero exit code). That matters if you run your script with set -e (to terminate on error).

Upvotes: 2

Related Questions