Bashユーザー入力を使用してファイルの値を変更する

Bashユーザー入力を使用してファイルの値を変更する

config.py以下を含むファイルがあります。

config['port'] = 11111

このファイルを編集したいです。難しい部分は、私がbash入力した値を11111に入力した値に置き換えたいということです。

ベストアンサー1

これはどうですか:

#!/bin/bash
# script.sh

# Prompt the user for input
echo "Choose a port number: "

# Read the input to a variable
read PORT

# Update the configuration file
sed -i "s/^\(config\['port'\] =\)\s\+[0-9]\+$/\1 ${PORT}/" config.py

これが入力ファイルの場合:

# config.py
config['port'] = 123

コマンドの実行方法は次のとおりです。

user@host:~$ bash script.sh
Choose a port number: 456

その後、更新されたファイルは次のようになります。

# config.py
config['port'] = 456

おすすめ記事