将值从一个文件替换为另一个文件

时间:2017-08-14 16:46:02

标签: bash awk replace grep tags

尝试找出一种方法,使用bash或awk或grep以最简单的方式将一个文件中的值替换为另一个文件的值。

示例:

文件1 - 包含节点上运行的所有docker容器映像的列表,以便:

搬运工/容器名称:123456

搬运工/ anothercontainer-differentname:7841216

文件2 - 是一个json格式的docker撰写文件,其中包含一个名为&#34的图像;图像:"包含这样的值:

image:docker / container-name:latest

image:docker / anothercontainer-differentname:latest

比较这两个文件并在标记"之后获取文件1中的值的最佳方法是什么:"匹配名称并替换文件2中的值"最新"所以文件2现在显示

image:docker / container-name:123456

container-name:
  image: docker/container-name:latest
  ports:
    - 80
    - 50051
  mem_limit: 134217727
  cpu_shares: 100
  environment:
    SERVICE_NAME: container-name
    CONSUL_SERVER: consul.service.consul:8500/v1/kv/lde/
    SERVICE_80_CHECK_HTTP: "/health"
    SERVICE_50051_CHECK_TCP: "true"
  depends_on:
    - service-name
  network_mode: "bridge"

1 个答案:

答案 0 :(得分:0)

好的我有一些适用于yaml文件的东西。我必须说,这有点哈哈。

# Delimiter is optional white space around column
awk -F "[ \t\n]*:[ \t\n]*" '
# Pass on the first file. Save an array like a[containerName] = tag
NR==FNR {a[$1]=$2; next}
# For the second file only process lines that contain image
/image/ {
   # Image name contains a slash. Escape that (for sed)
   imgName=$2;
   sub(/\//,"\\\\/",imgName);
   #  print the command for the sed
   print  "s/image: "imgName":"$3"/image: "imgName":"a[$2]"/g"
} ' file1 file2  | \
# Call sed multiple times in place, modifying the input file.
xargs -I@   sed -i  '@' file2

行动中:

$ cat file1
docker/container-name:123456
docker/anothercontainer-differentname:7841216

前的

文件2

$ cat file2
container-name:
  image: docker/container-name:latest
container-name:
  image: docker/anothercontainer-differentname:latest

文件2

$ cat file2
container-name:
  image: docker/container-name:123456
container-name:
  image: docker/anothercontainer-differentname:7841216