bash - Replace value from one file to another -
trying figure out way replace value 1 file value of using bash or awk or grep whichever easiest.
example:
file 1 - contains list of docker container images running on node so:
docker/container-name:123456
docker/anothercontainer-differentname:7841216
file 2 - docker compose file in json format field named "image:" contains values this:
image: docker/container-name:latest
image: docker/anothercontainer-differentname:latest
what best way compare 2 files , values file 1 after tag ":" matching name , replace value in file 2 "latest" file 2 shows
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"
ok have works on yaml file. little bit hacky must say.
# delimiter optional white space around column awk -f "[ \t\n]*:[ \t\n]*" ' # pass on first file. save array a[containername] = tag nr==fnr {a[$1]=$2; next} # second file process lines contain image /image/ { # image name contains slash. escape (for sed) imgname=$2; sub(/\//,"\\\\/",imgname); # print command sed print "s/image: "imgname":"$3"/image: "imgname":"a[$2]"/g" } ' file1 file2 | \ # call sed multiple times in place, modifying input file. xargs -i@ sed -i '@' file2
in action:
$ cat file1 docker/container-name:123456 docker/anothercontainer-differentname:7841216
file 2 before
$ cat file2 container-name: image: docker/container-name:latest container-name: image: docker/anothercontainer-differentname:latest
file 2 after
$ cat file2 container-name: image: docker/container-name:123456 container-name: image: docker/anothercontainer-differentname:7841216
Comments
Post a Comment