Loop through the lines of a file and print parts of it in sequence

Asked

Viewed 94 times

1

I have a text file that has several lines separated by two points. See for example:

teste1:testee1
teste2:testee2
teste:testeeee

Using a loop for, I’m trying to get the script to print on the screen the first part and then the second part, for example like this:

$ teste1
$ testee1
$ teste2
$ testee2
# Assim vai indo...

I just don’t understand why he’s just printing everything on the screen before the two dots, and then picking up the part after the two dots. Example of how it’s coming out:

$ teste1
$ teste2
$ teste
# agora começa a imprimir a parte depois dos dois pontos, o que está errado
$ testee1
$ testee2
$ testeeeee

Script code:

for IA in "$(cat teste.txt)"; do
STR1="$(echo "$IA" | cut -d ":" -f1)" #pega a primeira palavra depois dos dois pontos.
STR2="$(echo "$IA" | cut -d ":" -f2)" #pega a segunda palavra depois dos dois pontos.

echo "$STR1"
echo "$STR2"

sleep 3
done

1 answer

2


First let’s modify your loop a little bit:

for IA in "$(cat teste.txt)"; do
  echo "- $IA"
done

That is, before each line, I am also printing a hyphen. The output is:

- teste1:testee1
teste2:testee2
teste:testeeee

That is, all content was considered a "line" only.


This problem is explained in more detail here, and a solution would be to do something like:

while read LINE
do
...
done < file.txt

But if the last line of the file does not have a line break, it will be ignored, then the most guaranteed way (removed from here) is:

while IFS= read -r IA || [ -n "$IA" ]
do
  STR1="$(echo "$IA" | cut -d ":" -f1)" 
  STR2="$(echo "$IA" | cut -d ":" -f2)"
  
  echo "$STR1"
  echo "$STR2"

  sleep 3
done < teste.txt

With that the way out will be:

teste1
testee1
teste2
testee2
teste
testeeee

Browser other questions tagged

You are not signed in. Login or sign up in order to post.