简体   繁体   中英

Shell script to migrate config file variables

I need a way to migrate variables from one config file to the next/newer file during an update script on an embedded system using shell scripting.

I have a config file structured to be read by CGI-Scripts and C programs:

[Version]
api_version = 10

[Broadcast]
ip = 239.10.10.10
port = 35680

[Transmission]
uuid_long = YES

During the update process, I need to take the new file which will be similarly structured, and copy the values from the older file. Any values that exist in the old file will exist in the new, however not all the fields in the new file will exist in the old.

My thought is to loop through the file looking for the key = value\\n pattern, and performing a replacement in the new file, but I'm not sure how to do a grep that would strip that into 2 values I can use, and then do a sed that will match against the key and the new line character without knowing the value in the new file.

Note: I only have 'sh' to work with, no bash, if that makes a difference. (Embedded System)

Thank you for the suggestion to use AWK. I am very weak at shell scripting, so if there are improvements that can be made please advise.

#!/bin/sh
# Collect all the keys from the original config file
KEYS=$(awk '{ if ($1 !~ /\[[A-Za-z]*\]/ && $1 != "") print $1, "\n" }' /etc/file.conf)
# Loop through they keys replacing the values in the new config file
for KEY in $KEYS
do
        VALUE=$(awk -v key="$KEY" '{ if($1 ~ key) print $3 }' /etc/file.conf)
        sed -i "s/$KEY.*/$KEY = $VALUE/g" /etc/new.file.conf
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM