Bash loop, print current iteration?

Steven Penny picture Steven Penny · Jun 8, 2012 · Viewed 41.8k times · Source

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.

Answer

jordanm picture jordanm · Jun 8, 2012

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.