Bash loop, print current iteration? Bash loop, print current iteration? bash bash

Bash loop, print current iteration?


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

count=0while 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.txtfor 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.


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 linedo    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


n=0cat test.txt | while read line; do  printf "%7s %s\n" "$n" "${line#*//}"  n=$((n+1))done

This will work in Bourne shell as well, of course.

If you really want to avoid incrementing a variable, you can pipe the output through grep or awk:

cat test.txt | while read line; do  printf " %s\n" "${line#*//}"done | grep -n .

or

awk '{sub(/.*\/\//, ""); print NR,$0}' test.txt