Question

How can I loop through a file, in bash, and echo the line and line number?

I have this, which has everything but the line number:

while read p;
do
echo "$p" "$LINE";
done < file.txt

Thanks for your help!

edit this will be run multi-thread using xargs, so i don't want to use a counter.

No correct solution

OTHER TIPS

I would just use cat -n file

But if you really want to use a bash loop:

i=0
while read; do
  printf '%d %s\n' $(( ++i )) "$REPLY"
done < file

Update: I now prefer nl to cat -n, as the former is standard. To get the same result as cat -n, use nl -b a "$file".

You can use awk:

awk '{print NR,$0}' file.txt

You can use awk:

awk '{print NR "\t" $0}' file.txt

Or you can keep a count of the line number in your loop:

count=0
while read line
do
    ((count+=1))
    printf "%5d:   %s\n" "$count" "$line"
done

Using printf allows you to format the number, so the lines in the file are all lined up.

Just for fun, bash v4

mapfile lines < file.txt
for idx in "${!lines[@]}"; do printf "%5d %s" $((idx+1)) "${lines[idx]}"; done

Don't do this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top