How can I print all my docker container without losing the column headers?

Viewed 559

The command docker container ls -a lists all the docker containers, that are registered on your system (started and stopped ones), in that format:

CONTAINER ID   IMAGE                    COMMAND                  CREATED       STATUS                      PORTS                                                                                      NAMES
1e1cabc6ad32   hello-world              "/hello"                 7 days ago    Exited (0) 7 days ago                                                                                                  abcdef

Furthermore I am aware of docker's format command:

docker container ls -a --format '{{.Names}}'

This one lists only the image names, which is what I try to achieve, however I do not want to lose those column headers. So I tried playing around with awk:

docker container ls -a | awk '{print $2}'

This one for example lists me the image types, but the column becomes ID because the first column has the heading CONTAINER ID with a white space in it.

The longer the table gets, the more mistakes get in with this easy awk command. I noticed that all entries inside a column have only 1 whitespace, but the separators between the columns have 3 white spaces.

So my questions is how I can get an array by awk that separates me the entries like that? I guess there is something already asked like this, but I couldn't find anything since I am not really familiar with awk.

2 Answers

You can just use the table keyword/directive to include the headers. For example:

$ docker container ls -a --format 'table {{.ID}}\t{{.Names}}'
CONTAINER ID   NAMES
9b9fce78d02d   upbeat_goodall
f9a1b191eecd   xenodochial_mclaren
ea72b3b4a8de   exciting_gould
990405ea87d1   strange_colden
bb2cffd1f514   youthful_agnesi
58e684d6d61f   brave_darwin

If the output needs to be parsed, consider instead writing JSON, which can be easily parsed using jq on the command-line for example:

docker container ls -a --format='{{json .}}' | jq -r '.'

As mentioned in the question, that the fields are separated by more than 3 spaces, below is an awk solution.

awk 'BEGIN {FS="[[:space:]]{3,}"; OFS="\t"}{print $1OFS$NF}' <(docker container  ls -a)
Related