Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through file and echo each line with line number

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.

like image 323
d-_-b Avatar asked Oct 20 '25 12:10

d-_-b


1 Answers

I would just use nl -b a 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: A previous version suggested cat -n. I now prefer nl to cat -n, as the former is standard.

like image 75
kojiro Avatar answered Oct 23 '25 03:10

kojiro