简体   繁体   中英

How to get the value via Linux command 'grep'

I want to get some specific information with docker api. In this case, I want to get the IMAGE ID that correspond to <none> of REPOSITORY with command docker images

$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
<none>              <none>              ebeb5aebbeef        5 minutes ago       479MB
build-embed         latest              80636e4726f8        10 minutes ago      479MB
<none>              <none>              a2abf2e07bc3        About an hour ago   1.38GB
ubuntu              18.04               4e5021d210f6        5 weeks ago         64.2MB

I tried the command as below:

$ docker images | grep `<none>'

And get results:

<none>              <none>              ebeb5aebbeef        2 minutes ago       479MB
<none>              <none>              a2abf2e07bc3        58 minutes ago      1.38GB

How can I just only get the IMAGE ID ? (like ebeb5aebbeef a2abf2e07bc3 )

The purpose of this question is that I want to remove <none> images with docker api, like docker rmi $(docker images | grep <none>

Thank you all

Use awk to get just the third field of the matching lines.

docker images | awk '$1 == "<none>" { print $3 }'

Don't use grep '<none>' since that can match in fields other than the REPOSITORY .

Use --filter option with -q option, instead of listing all images and filtering them using grep

docker images -f "dangling=true" -q

The docker images command has a couple of options to do this more directly, without trying to parse apart its output.

docker images -f can filter the list of images presented on a minimal set of conditions. One of those conditions is "dangling", which is exactly those images with <none> labels. This can replace your grep command.

docker images -q prints out only the image IDs and not the rest of the line. This can replace the awk command from @Barmar's answer .

This would leave you with

docker images -f dangling=true -q

to print out the image IDs of <none> images, which is what you're after; and thereby

docker images -f dangling=true -q | xargs docker rmi

to remove them.

Also consider docker system prune which will remove dangling images, and also stopped containers and unused networks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM