-1

How to automatically count number of lines printed by each command?

Examples:

$ echo xxx
xxx
1

$ ls -1
xxx
yyy
zzz
3

$ > t0.txt
0

etc.

I.e. how to correctly add | wc -l into .bashrc?

5
  • 3
    I don't think this is possible. Perhaps if you can explain why you're looking for this, sometime may be able to provide a more direct solution to the underlying requirement Commented Feb 15, 2022 at 19:44
  • @roaima It is simple: I frequently count the number of lines printed by a command via | wc -l. So I am thinking to automate it. Commented Feb 16, 2022 at 0:03
  • Counting output is fairly straightforward in the specific case, sure. But remember what you're asking isn't simply to add | wc -l to everything because you want to see the output too. I'm responding to your "how do I do this automatically for everything". I don't think it's possible Commented Feb 16, 2022 at 7:04
  • @roaima Re: "I don't think it's possible": can you elaborate? What exactly makes you to think so? What are the obstacles? Can the impossibility (if so) be formally proven? Commented Feb 17, 2022 at 22:51
  • I'm stating an opinion qualified by over 30 years using UNIX style systems. (It doesn't mean I'm right, mind.) I don't believe there is any mechanism, short of reimplementing a shell (possibly in shell script), that allows you to send all cooked output to another command that can then send it on to the terminal and also count the number of lines. You'd have to convince the calling program it was talking to a terminal (contrast ls with ls | cat) and also know to step aside gracefully if you fired up a full screen editor such as vi Commented Feb 17, 2022 at 22:57

1 Answer 1

0

Combination of many commands, using Bash:

ls -1 \
    | cat <(echo) - \
    | cat -n \
    | tac \
    | cat -n \
    | while read i n line; do
        if [[ $i == 1 ]]; then
            echo $((n - 1))
        fi
        echo $line
    done \
    | tac \
    | tail -n +2

Output:

xxx
yyy
zzz
3
  • cat <(echo) - adds an empty line to the head because if stdin is zero lines, the code block above will not work correctly
  • cat command with n option adds line number to head
  • tac command reverses stdin
  • In while loop, print reversed first line number and stdin
  • finally, tac again and tail -n +2 to print the expected output
  • It works too replace ls -1 with echo xxx, > t0.txt, etc.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.