Skip to content

Instantly share code, notes, and snippets.

@teroyks
Last active November 17, 2021 09:17
Show Gist options
  • Save teroyks/edbfd7b75f17239ccffefcb94b6338eb to your computer and use it in GitHub Desktop.
Save teroyks/edbfd7b75f17239ccffefcb94b6338eb to your computer and use it in GitHub Desktop.
Output a running count of lines

linecounter2 is an alternate version that goes to the previous line, erases it and rewrites with new info. Might be useful if you need the newline character at the end of the string (for example to flush an output buffer).

#!/usr/bin/env bash
# Output a running counter of lines passed to the script.
# Optionally, if you know the total count you can give it as an argument.
#
# Example (bash):
# for i in $(seq 50000); do echo "line content"; done | linecounter 50000
#
# To preserve the original output, use tee:
# for i in $(seq 50000); do echo "line content"; done | tee output.log | linecounter 50000
line_nr=0
while read -r line; do
line_nr=$((line_nr + 1))
printf "\r%'d" $line_nr
test -n "$1" && printf "/%'d" $1
done
echo
#!/usr/bin/env bash
# Output a running counter of lines passed to the script.
# Optionally, if you know the total count you can give it as an argument.
#
# Example (bash):
# for i in $(seq 50000); do echo "line content"; done | linecounter 50000
#
# To preserve the original output, use tee:
# for i in $(seq 50000); do echo "line content"; done | tee output.log | linecounter 50000
line_nr=0
echo
while read -r line; do
line_nr=$((line_nr + 1))
tput cuu1 # move cursor up 1 line
tput el # erase line
printf "%'d" $line_nr # output number formatted according to locale
test -n "$1" && printf "/%'d" $1 # output total amount if given
echo
done
@teroyks
Copy link
Author

teroyks commented Nov 16, 2021

Demo:

linecounter_demo.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment