如何修改檔案中的變數

如何修改檔案中的變數

我有一個這樣的設定檔:

# Default LIST="nil"
LIST="element1 element2 element3"

從 shell 腳本修改 LIST 最簡單的方法是什麼?

答案1

使用sed

sed -i 's/LIST\=.*/LIST="element4 element5"/' config_file

如果您只想在未註解的情況下更新 LIST,請新增^(行首):

sed -i 's/^LIST\=.*/LIST="element4 element5"/' config_file

答案2

與已接受的答案相同,但可以在腳本。如果有人發現它有用:

#! /bin/bash
#  (GPL3+) Alberto Salvia Novella (es20490446e)


modifyVariableInFile () {
    variable="${1}"
    content="${2}"
    file="${3}"

    if [ ! -f "${file}" ]; then
        echo "modifyVariableInFile: file doesn't exist: ${file}"
        exit 1
    fi

    sed -i "s/^${variable}\=.*/${variable}=\"${content}\"/" "${file}"
}


modifyVariableInFile ${@}

相關內容