Before we begin, we’ll assign a variable with a multi-line value for demonstration purposes:
Here’s how to isolate any arbitrary line from $multiline (where $counter can be any non-zero positive integer)…
And finally, here’s how to write a while-loop that parses each line and prints that line’s index alongside it…
The while-loop will print empty lines with their index too, so you’ll need to check if the value of $line is non-empty before printing it if you want to skip empty lines.
The wc -l
command counts the number of newline characters in a string, and not necessarily the number of lines, so a string like test\nline would be counted as one “line” and not two. Thankfully, the above script works regardless of if the value of $multiline ends with a newline character or not (and it ignores extraneous newlines at the end… for some reason).