0

I have a config.py file containing

config['port'] = 11111

I want to edit this file. The tricky part is I want bash to take input from me and replace 11111 with the input i give.

Inian
  • 12,472
  • 1
  • 35
  • 52
Ayush Mishra
  • 33
  • 1
  • 7
  • Is that the only line in your config.py file? What do you mean by take input? Do you want it to prompt for input or would you like to enter your input as a parameter? What have you tried so far to accomplish this? – jesse_b Dec 02 '17 at 15:02
  • I want To Take Input Using read `'Port' avar` – Ayush Mishra Dec 02 '17 at 15:05
  • post the expected result – RomanPerekhrest Dec 02 '17 at 15:07
  • 1
    I suggest that you instead modify the Python script to read the desired port from another standalone file. The idea of a bash script written just to interactively modify a Python script makes me cringe. It would make you cringe, too, if you had to maintain it. – Wildcard Dec 02 '17 at 15:16
  • Also see [Why is using a shell loop to process text considered bad practice?](http://unix.stackexchange.com/q/169716/135943) – Wildcard Dec 02 '17 at 15:16
  • while you're reading, don't forget our [welcome tour](https://unix.stackexchange.com/tour)! – Jeff Schaller Dec 02 '17 at 15:26

2 Answers2

3

How about this:

#!/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

If this is your input file:

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

And this is how you execute the command:

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

Then this is your updated file:

# config.py
config['port'] = 456
igal
  • 9,666
  • 1
  • 42
  • 58
0
new_port=12345
awk -v port="$new_port" '$0=="config['\'port\''] = 11111" { sub("11111",port); };
    { print; }' /path/to/file
Hauke Laging
  • 88,146
  • 18
  • 125
  • 174