Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash loop, print current iteration?

Say you have a simple loop

while read line do   printf "${line#*//}\n" done < text.txt 

Is there an elegant way of printing the current iteration with the output? Something like

 0 The 1 quick 2 brown 3 fox 

I am hoping to avoid setting a variable and incrementing it on each loop.

like image 595
Zombo Avatar asked Jun 08 '12 03:06

Zombo


People also ask

How do you execute a loop in bash?

To demonstrate, add the following code to a Bash script: #!/bin/bash # Infinite for loop with break i=0 for (( ; ; )) do echo "Iteration: ${i}" (( i++ )) if [[ i -gt 10 ]] then break; fi done echo "Done!"

What is #!/ Bin bash?

#!/usr/bin/bash is a shebang line used in script files to set bash, present in the '/bin' directory, as the default shell for executing commands present in the file. It defines an absolute path /usr/bin/bash to the Bash shell.


2 Answers

To do this, you would need to increment a counter on each iteration (like you are trying to avoid).

count=0 while read -r line; do    printf '%d %s\n' "$count" "${line*//}"    (( count++ )) done < test.txt 

EDIT: After some more thought, you can do it without a counter if you have bash version 4 or higher:

mapfile -t arr < test.txt for i in "${!arr[@]}"; do    printf '%d %s' "$i" "${arr[i]}" done 

The mapfile builtin reads the entire contents of the file into the array. You can then iterate over the indices of the array, which will be the line numbers and access that element.

like image 94
jordanm Avatar answered Sep 26 '22 03:09

jordanm


You don't often see it, but you can have multiple commands in the condition clause of a while loop. The following still requires an explicit counter variable, but the arrangement may be more suitable or appealing for some uses.

while ((i++)); read -r line do     echo "$i $line" done < inputfile 

The while condition is satisfied by whatever the last command returns (read in this case).

Some people prefer to include the do on the same line. This is what that would look like:

while ((i++)); read -r line; do     echo "$i $line" done < inputfile 
like image 44
Dennis Williamson Avatar answered Sep 24 '22 03:09

Dennis Williamson