Show particular column for command

Viewed 8400

I want to show only specific columns for all the records in the command.

Example: docker ps shows me data in 10 columns. It can have space in between the column headers. My requirement is to get only 2-4 columns in some sequence.

Is there a direct way to do that in any of the commands that respond in a tabular way?

I am new to Linux and thinking if this can be feasible. Thanks.


For example:

$ docker ps
CONTAINER ID  IMAGE   COMMAND     CREATED             NAMES
123           image   "ABC DEF"   10 hours ago        image ABC

Here in the above scenario, CONTAINER ID is one header column but there is space, and in the row for NAMES columns can have space in between.

Using AWK, CUT etc it is trickier to write a common script for all the commands because they work on "space" logic.

3 Answers

You can use awk like that:

$ ps | awk '{print $2 " " $3 " " $4}'
TTY TIME CMD
pts/22 00:00:00 bash
pts/22 00:00:00 ps
pts/22 00:00:00 awk

Or together with column -t for more readable output:

$ ps | awk '{print $2 " " $3 " " $4}' | column -t
TTY     TIME      CMD
pts/22  00:00:00  bash
pts/22  00:00:00  ps
pts/22  00:00:00  awk
pts/22  00:00:00  column

As William Pursell noted in the comment below awk command can be simplified:

$ ps | awk '{print $2, $3, $4}' | column -t
TTY    TIME      CMD
pts/9  00:00:00  bash
pts/9  00:00:00  ps
pts/9  00:00:00  awk
pts/9  00:00:00  column

Piping the output to tr and cut:

docker ps | tr -s " " | cut -d " " -f 2-4

-s flag on tr squeezes characters and leaves only one " "

-d on cut tells to split field by " ".

Sample output using Perl. Perl has 0 based index, so you have to use 1..3 meaning from 2 to 4

$ ps
      PID    PPID    PGID     WINPID   TTY         UID    STIME COMMAND
    14556   11424   14556       6944  cons0     197609 22:10:27 /usr/bin/ps
    11424       1   11424      11424  cons0     197609 22:41:21 /usr/bin/bash
$ ps | perl -F'\s+' -lane ' print "@F[1..3]" '
PID PPID PGID
11208 11424 11208
11424 1 11424
380 11424 11208

If you don't need headers.. then

$ ps | perl -F'\s+' -lane 'if($.>1) { print "@F[1..3]" } '
6072 11424 6072
11424 1 11424
Related