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

问题描述:

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

实施例:

文件1 - 包含一个节点,以便上运行的所有搬运工容器的图像的列表:

搬运工/容器名称:123456

搬运工/ anothercontainer-differentname:7841216

文件2 - 是json格式的码头工具文件,其文件名为“image:”,其中包含以下值:

图片:泊坞窗/容器名称:最新

图像:泊坞窗/ anothercontainer-differentname:最新

什么会是比较两个文件,并从标签“后,文件1得到的值的最佳方式: “为匹配的名称和替换文件值2‘最新’,使文件2现在显示

图像:泊坞窗/容器名称: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" 
+0

用于修改搬运工撰写JSON,我建议[JQ](HTTPS ://stedolan.github.io/jq/) –

+0

可以哟你提供了一个docker撰写文件的例子吗? –

+0

@HakanBaba新增 –

好吧,我有东西在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 [email protected] 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 
+0

@Ezekiel Watchman让我知道这是否适合你。根据您的容器名称,可能会出现一些失败的情况。 –

+0

天才,工作就像一个魅力 –