Remove Docker Images with awk


Docker images can take up a lot of space, so occasionally I want to clean them up.

When listing Docker images we see this format, here with my Docker images for R:

$ docker image ls
r-base        4.0.0    1dd56183fab0
r-minimal     4.0.0    1bf766801449
r-deps        4.0.0    fe612b00eef0
r-base        3.6.3    e55cf96ae0b6
r-minimal     3.6.3    4514e189d05a
r-deps        3.6.3    4b8d6ca5dc70

I have left out the CREATED and SIZE columns, since they are of no interest in this post.

My task is to remove the old versions with the tag 3.6.3. This can of course be done by spelling out all the images:

docker image rm r-deps:3.6.3 r-minimal:3.6.3 r-base:3.6.3 

Alternatively, the docker image rm command accepts the IMAGE ID. With the columnar format the filtering and extration of IMAGE IDs fits right in the neat awk language.

For starters, we can select only the lines with 3.6.3:

docker image ls | awk '$2 == "3.6.3"'

To only print the IMAGE ID from the selected lines we can do like this:

docker image ls | awk '$2 == "3.6.3" { print $3 }'

By combining this with the rm command we delete the images:

docker image rm `docker image ls | awk '$2 == "3.6.1" { print $3 }'`

If further filtering is needed the match can be narrowed, e.g. by requiring that the first column starts with r-:

docker image ls | awk '$2 == "3.6.3" && $1 ~ "^r.*"'
>> Home