0

I want to use grep to only see a certain column from the output of a Linux command. When I use this command, I get the following output:

$ ps ax | grep sshd | grep  'priv' | sort -k 3
     4886 ?        Ss     0:00 sshd: vpnuser002 [priv]
      10637 ?        Ss     0:00 sshd: vpnuser003 [priv]
      10651 ?        Ss     0:00 sshd: vpnuser003 [priv]
      11594 ?        Ss     0:00 sshd: vpnuser003 [priv]
      11669 ?        Ss     0:00 sshd: vpnuser003 [priv]
      11817 ?        Ss     0:00 sshd: vpnuser003 [priv]
       9680 ?        Ss     0:00 sshd: vpnuser003 [priv]
       4034 ?        Ss     0:00 sshd: vpnuser006 [priv]

What must I change in my command to only see the last column? Like this:

    sshd: vpnuser002 [priv]
    sshd: vpnuser003 [priv]
    sshd: vpnuser003 [priv]
    sshd: vpnuser003 [priv]
    sshd: vpnuser003 [priv]
    sshd: vpnuser003 [priv]
    sshd: vpnuser003 [priv]
    sshd: vpnuser006 [priv]

I am using Ubuntu Linux.

1
  • Do you have to use grep? cut is better suited for the task I think.
    – Krackout
    Commented Feb 13, 2023 at 11:30

2 Answers 2

1

You could output the command column with o command without header h and then grep for the specific output:

ps axho command | grep '^sshd:.*\[priv\]$' | sort
1

Like this:

$ <INPUT> | grep -o '\bsshd: .*\[priv\]$'

or

ps -C sshd all | grep -o '\bsshd: .*\[priv\]$'

Output

sshd: vpnuser002 [priv]
sshd: vpnuser003 [priv]
sshd: vpnuser003 [priv]
sshd: vpnuser003 [priv]
sshd: vpnuser003 [priv]
sshd: vpnuser003 [priv]
sshd: vpnuser003 [priv]
sshd: vpnuser006 [priv]

The regular expression matches as follows:

Node Explanation
\b the boundary between a word char and something that is not a word char
sshd: 'sshd: '
.* any character except \n (0 or more times (matching the most amount possible))
\[priv\]$ '[priv]', at the end of line: '$'
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .