Post

Linux - 批量文本处理 删除

批量文本处理 删除

Docker 镜像,删除名为 none 的那些:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
$ docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
api-adapter         v1                  e9bc8e28af2a        3 hours ago         7.67MB
<none>              <none>              f0fa889be9e8        2 days ago          956MB
<none>              <none>              257954316455        2 days ago          956MB
<none>              <none>              99739acbfe7a        2 days ago          956MB
<none>              <none>              52b10754a70c        2 days ago          956MB
<none>              <none>              86878eefdd39        2 days ago          956MB
golang              1.10                0a19f4d16598        12 days ago         729MB
python              3                   1e80caffd59e        12 days ago         923MB

1. manually

$ docker image rm f0fa889be9e8



2. 文本过滤 - grep

$ docker images | grep none
<none>              <none>              f0fa889be9e8        2 days ago          956MB
<none>              <none>              257954316455        2 days ago          956MB
<none>              <none>              99739acbfe7a        2 days ago          956MB
<none>              <none>              52b10754a70c        2 days ago          956MB
<none>              <none>              86878eefdd39        2 days ago          956MB


3. 字段提取 - awk
通过 cut 命令进行 字段切分 也可以得到相同的结果。
cut 只能按单个字符进行切分,而原文本中的空格为多个,因此需要先进行 文本替换 。

$ docker images | grep none | awk '{print $3}'
f0fa889be9e8
257954316455
99739acbfe7a
52b10754a70c
86878eefdd39



4. 文本替换 - sed
将一个或多个空格替换成一个:

$ docker images | grep none | sed 's/  */ /g'
<none> <none> f0fa889be9e8 2 days ago 956MB
<none> <none> 257954316455 2 days ago 956MB
<none> <none> 99739acbfe7a 2 days ago 956MB
<none> <none> 52b10754a70c 2 days ago 956MB
<none> <none> 86878eefdd39 2 days ago 956MB



5. 文本切分 - cut 命令对结果进行进一步切分并取出第三个字段:

$ docker images | grep none | sed 's/  */ /g' | cut -d ' ' -f 3
f0fa889be9e8
257954316455
99739acbfe7a
52b10754a70c
86878eefdd39



6. 批量删除 - xargs 批量删除镜像:

$ docker images | grep none | sed 's/  */ /g' | cut -d ' ' -f 3 | xargs docker image rm
$ docker images | grep none | awk '{print $3}' | xargs docker image rm
Deleted: sha256:f0fa889be9e8f8369353a32e8cec17e9333cbeb581de5f78bf6875917d971bc9
Deleted: sha256:d301d0546b29b7daa55d29f29d9253664870fd83465aefe8b92ff6a7048d5612
=
$ docker image rm f0fa889be9e8 257954316455 99739acbfe7a 52b10754a70c 86878eefdd39



This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.