Sunday, April 28, 2024
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 1449  / 3 Years ago, tue, may 18, 2021, 10:40:12

I am working on a script to configure a server. Basically the script installs several services and copies configuration files in to place.



I would like to replace the username in one of the configuration files with the content of another file.
The input file is one line of text which contains the username.
The config file has multiple lines of text but only one line refers to the username.



How do I replace the username of the config file with the username stored in the input file?


More From » command-line

 Answers
4

Assuming the actual username in the targeted file is preceded by USER: (if not, change it in the head section of the script), here is a python solution to do the job.



Simply copy the script into an empty file, save it as replace_username.py and run it with the source file (with the correct user name) and the destination file as arguments:



python3 /path/to/replace_username.py <sourcefile> <destination_file>


The script:



#!/usr/bin/env python3

import sys

source = sys.argv[1] # the file with the password you want to insert
destination = sys.argv[2] # the targeted configuration file
prefix="USER:" # prefix, check if it is exactly as in your files

with open(source) as src:
name = src.read().strip()

with open(destination) as edit:
lines = edit.readlines()

for i in range(len(lines)):
if lines[i].startswith(prefix):
lines[i] = prefix+name+"
"

with open(destination, "wt") as edit:
for line in lines:
edit.write(line)

[#22658] Wednesday, May 19, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
naldis

Total Points: 257
Total Questions: 101
Total Answers: 111

Location: Kenya
Member since Sat, Feb 25, 2023
1 Year ago
;