0

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?

  • How could you identify the line containing the user name in both files? – Jacob Vlijm Oct 26 '14 at 19:29
  • Hello Jacob, In the input file there is just one word which is the username. In the config file the place where I have to enter the user name is in the line USER:'username' – Steven Brian Oct 26 '14 at 20:15
  • Ah, I see, will edit the answer. – Jacob Vlijm Oct 26 '14 at 20:16
  • I edited my answer. Now the script assumes the source file only contains the username, in the targeted config file everything after USER: is replaced by the username in the sourcefile. – Jacob Vlijm Oct 26 '14 at 20:30
  • I tested the script and it works. Thank you for your help! – Steven Brian Oct 26 '14 at 20:40
0

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+"\n"

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

You can save the username in a variable and use sed to change the configfile:

#! /bin/bash
username=$(< /path/to/username)
sed -i~ -e "s/username=XXX/username=$username/"

The config file in this example should contain the line username=XXX. The username shouldn't contain / (some other non-alphanumeric characters might be problematic, too).

(Untested.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.