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.
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!"
#!/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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With