Welcome to the Linux Foundation Forum!

Print output based on line count

Options

I have a req where the output should be printed only if the command result is more than 1 line.

Eg:

ps aux | grep S -> gives output as
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 6554 10.0 1 0.0 126 xx x S+ 04:44 0:00 grep --color=auto S
root 6554 10.0 1 0.0 126 xx x S+ 04:44 0:00 grep --color=auto S

if the output is just one line as below
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

I should not print anything.

How to do this ?

Answers

  • afmorielo
    afmorielo Posts: 9
    edited October 2021
    Options

    From your post, I believe your question is: "How to print output based on line count?"
    My suggested solution uses an if statement and the "wc" utility in Linux. Manpage: https://linux.die.net/man/1/wc

    Solution 1 - simple
    The problem with this solution is that you have to run the command twice - once to get the number of lines, and a second time to actually print the output

    if [ $(ps aux | grep S | wc -l) -gt 1 ]; then
    ps aux | grep S;
    fi

Categories

Upcoming Training