2017-08-14 100 views
0

嘗試找出一種方法,使用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新增 –

回答

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 [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

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

相關問題